package com.xjscrm.console.service.customer.wwCustomer.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.msg.consertoserver.MicaCustomerAddTagMsg;
import com.uzai.mobile.collect.api.dto.trigger.*;
import com.uzai.mobile.collect.api.enums.MicaMsgType;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.constant.CacheKey;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.*;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.utils.ww.WwApiUtil;
import com.xjscrm.common.utils.ww.dto.WwTagAddDTO;
import com.xjscrm.common.utils.ww.dto.WwTagAddResultDTO;
import com.xjscrm.common.utils.ww.dto.WwTagGetResultDTO;
import com.xjscrm.console.chat.frame.recv.RPullCustomerMsg;
import com.xjscrm.console.common.util.MyExcelUtil;
import com.xjscrm.console.entity.MerchatChildDeviceRelation;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.mq.producer.SendMsgProducer;
import com.xjscrm.console.param.BaseDto;
import com.xjscrm.console.param.group.SheetHeader;
import com.xjscrm.console.param.group.WwGroupMemberQuery;
import com.xjscrm.console.param.group.WwGroupQuery;
import com.xjscrm.console.param.wwCustomer.*;
import com.xjscrm.console.param.wwDevice.WwDeviceQuery;
import com.xjscrm.console.service.common.corpapplication.CorpApplicationService;
import com.xjscrm.console.service.customer.corp.WwCorpService;
import com.xjscrm.console.service.customer.group.WwGroupService;
import com.xjscrm.console.service.customer.wwCustomer.CustomerService;
import com.xjscrm.console.service.customer.wwCustomer.WwCustomerService;
import com.xjscrm.console.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WwCustomerServiceImpl implements WwCustomerService {

    @Autowired
    private WwCustomerMapper wwCustomerMapper;

    @Autowired
    private WwTagsMapper wwTagsMapper;

    @Autowired
    private MerchatChildDeviceRelationMapper merchatChildDeviceRelationMapper;

    @Autowired
    private WwCustomerTagsMapper wwCustomerTagsMapper;

    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private SendMsgProducer sendMsgProducer;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CustomerBehaviorMapper customerBehaviorMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WhiteListMapper whiteListMapper;

    @Autowired
    private BlackListMapper blackListMapper;

    @Autowired
    private WwGroupMemberMapper wwGroupMemberMapper;


    @Autowired
    private WwGroupService wwGroupService;

    @Autowired
    private SyncCustomerJobMapper syncCustomerJobMapper;


    @Autowired
    private SyncTagJobMapper syncTagJobMapper;

    @Autowired
    private WwCorpService wwCorpService;
    @Autowired
    private CorpApplicationService corpApplicationService;

    @Autowired
    private WwCorpMapper wwCorpMapper;

    @Override
    public Object newTotalCustomerNumber(CustomerCountDto customerCountDto) {
        if (customerCountDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        Integer newTotalCustomerNumber = wwCustomerMapper.newTotalCustomerNumber(customerCountDto);
        return newTotalCustomerNumber;
    }

    @Override
    public Object countCustomerScene(CustomerCountDto customerCountDto) {
        if (customerCountDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        List<CountCustomerSceneVo> countCustomerSceneVos = wwCustomerMapper.countCustomerScene(customerCountDto);

        //获取查询出来已有的场景ID
        Set<Integer> existingScenes = countCustomerSceneVos.stream().map(CountCustomerSceneVo::getScene).collect(Collectors.toSet());

        //获取所有的场景ID
        Set<Integer> allScenes = new HashSet<>();
        for (WwFriendReqScene wwFriendReqScene : WwFriendReqScene.values()) {
            allScenes.add(wwFriendReqScene.getValue());
        }

        //获取没有的场景
        allScenes.removeAll(existingScenes);

        //将没有的场景加入
        if (allScenes != null && !allScenes.isEmpty()) {
            for (Integer scene : allScenes) {
                CountCustomerSceneVo countCustomerSceneVo = new CountCustomerSceneVo();
                countCustomerSceneVo.setScene(scene);
                countCustomerSceneVo.setUserCount(0);
                countCustomerSceneVo.setPercentage(0D);
                countCustomerSceneVos.add(countCustomerSceneVo);
            }
        }

        if (countCustomerSceneVos != null && !countCustomerSceneVos.isEmpty()) {
            try {
                for (CountCustomerSceneVo countCustomerSceneVo : countCustomerSceneVos) {
                    countCustomerSceneVo.setSceneDescByScene();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return countCustomerSceneVos;
    }


    @Override
    public Object countCustomerGender(CustomerCountDto customerCountDto) {
        if (customerCountDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        List<CountCustomerGenderVo> countCustomerGenderVos = wwCustomerMapper.countCustomerGender(customerCountDto);


        //获取查询出来已有的场景ID
        Set<Integer> existingGenders = countCustomerGenderVos.stream().map(CountCustomerGenderVo::getGender).collect(Collectors.toSet());

        //获取所有的场景ID
        Set<Integer> allGenders = new HashSet<>();
        for (GenderEnum genderEnum : GenderEnum.values()) {
            allGenders.add(genderEnum.getId());
        }

        //获取没有的场景
        allGenders.removeAll(existingGenders);

        //将没有的场景加入
        if (allGenders != null && !allGenders.isEmpty()) {
            for (Integer gender : allGenders) {
                CountCustomerGenderVo countCustomerGenderVo = new CountCustomerGenderVo();
                countCustomerGenderVo.setGender(gender);
                countCustomerGenderVo.setUserCount(0);
                countCustomerGenderVo.setPercentage(0D);
                countCustomerGenderVos.add(countCustomerGenderVo);
            }
        }

        if (countCustomerGenderVos != null && !countCustomerGenderVos.isEmpty()) {
            try {
                for (CountCustomerGenderVo countCustomerGenderVo : countCustomerGenderVos) {
                    countCustomerGenderVo.setGenderDescByGender();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return countCustomerGenderVos;
    }

    @Override
    public Object getCustomerTagTree(CustomerTagQuery customerTagQuery) {
        if (customerTagQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (customerTagQuery.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
//        if (customerTagQuery.getType() == 1 && StringUtils.isBlank(customerTagQuery.getCorpId())) {
//            return null;
//        }
        //创建默认分组
        if (customerTagQuery.getDeviceUniqueId() != null) {
            WwTags tags = wwTagsMapper.getdefultParentTag(customerTagQuery.getMerId(), customerTagQuery.getDeviceUniqueId());
            if (tags == null) {
                int time = DateUtil.getTime();
                WwTags wwTags = new WwTags();
                long id = IdWorker.getId();
                wwTags.setId(id);
                wwTags.setMerId(customerTagQuery.getMerId());
                wwTags.setType(2);
                wwTags.setTagName("默认");
                wwTags.setPid(0L);
                wwTags.setStatus(1);
                wwTags.setDeviceUniqueId(customerTagQuery.getDeviceUniqueId());
                wwTags.setCreateTime(time);
                wwTags.setUpdateTime(time);
                wwTags.setSysGroup(1);
                wwTagsMapper.insertWwTags(wwTags);
            }
        }

//        customerTagQuery.setStatus(1);
        List<WwTags> wwTagsList = wwTagsMapper.getCustomerTag(customerTagQuery);
//        List<WwTags> wwTagsList=wwTagsMapper.getCustomerTagTree(customerTagQuery);
        ArrayList<Map> arrayList = new ArrayList<>();
        if (wwTagsList != null && !wwTagsList.isEmpty()) {
            for (WwTags wwTags : wwTagsList) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("id", wwTags.getId());
                map.put("tagName", wwTags.getTagName());
                map.put("pid", wwTags.getPid());
                map.put("status", wwTags.getStatus());
                arrayList.add(map);
            }
        }
        return arrayList;
    }


    @Override
    public Long addCustomerPersonTag(CustomerTagDto customerTagDto) {
        if (customerTagDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (customerTagDto.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (customerTagDto.getPid() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (customerTagDto.getType() == 2 && customerTagDto.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (StringUtils.isBlank(customerTagDto.getTagName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        //查询所有的标签，查看是否有重复标签
        CustomerTagQuery customerTagQuery = new CustomerTagQuery();
        customerTagQuery.setMerId(customerTagDto.getMerId());
        customerTagQuery.setDeviceUniqueId(customerTagDto.getDeviceUniqueId());
        customerTagQuery.setType(2);
        List<WwTags> customerTag = wwTagsMapper.getCustomerTag(customerTagQuery);
        if (customerTag != null && !customerTag.isEmpty()) {
            List<String> customerTagNames = new ArrayList<>();
            customerTag.forEach(it -> customerTagNames.add(it.getTagName()));
            if (customerTagNames.contains(customerTagDto.getTagName())) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "重复的标签名");
            }
        }

        WwTags wwTags = new WwTags();
        int time = DateUtil.getTime();
        BeanUtil.copyProperties(customerTagDto, wwTags);
        long id = IdWorker.getId();
        wwTags.setId(id);
        wwTags.setStatus(0);
        wwTags.setDeviceUniqueId(customerTagDto.getDeviceUniqueId());
        wwTags.setCreateTime(time);
        wwTags.setUpdateTime(time);
        wwTagsMapper.insertWwTags(wwTags);

        mqAddTagId(wwTags.getTagName(), id, customerTagDto.getMerId(), customerTagDto.getDeviceUniqueId());

        return id;
    }

    private void mqAddTagId(String tagName, long id, Long merId, Long deviceUniqueId) {
        WwDevice wwDevice = wwDeviceMapper.getById(deviceUniqueId, merId);
        MicaTriggerChangeLabelMsg micaTriggerChangeLabelMsg = new MicaTriggerChangeLabelMsg();
        micaTriggerChangeLabelMsg.setLabelId(String.valueOf(0));
        micaTriggerChangeLabelMsg.setLabelName(tagName);
        micaTriggerChangeLabelMsg.setMessageId(id);
        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerChangeLabelMsg, MicaTriggerType.TRIGGER_CHANGE_LABEL);
        micaTriggerDto.setMerId(merId);
        micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
    }

    private void mqDeleTagId(WwTags wwTags, long id, Long merId, Long deviceUniqueId) {
        WwDevice wwDevice = wwDeviceMapper.getById(deviceUniqueId, merId);

        MicaTriggerChangeLabelMsg micaTriggerChangeLabelMsg = new MicaTriggerChangeLabelMsg();
        micaTriggerChangeLabelMsg.setLabelId(wwTags.getTagId());
        micaTriggerChangeLabelMsg.setLabelName(wwTags.getTagName());
        micaTriggerChangeLabelMsg.setMessageId(id);
        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerChangeLabelMsg, MicaTriggerType.TRIGGER_DEL_LABEL);
        micaTriggerDto.setMerId(merId);
        micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
    }


    @Override
    public MyPageInfo<WwCustomerVo> getCustomer(CustomerQuery customerQuery) {
        if (customerQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        if (customerQuery.getParentTagId() != null) {
            CustomerTagQuery customerTagQuery = new CustomerTagQuery();
            customerTagQuery.setIfChild(1);
            customerTagQuery.setMerId(customerQuery.getMerId());
            customerTagQuery.setStatus(1);
            customerTagQuery.setPid(customerQuery.getParentTagId());
            List<WwTags> wwTagsList = wwTagsMapper.getCustomerTag(customerTagQuery);
            List<Long> customerIds = new ArrayList<>();
            if (wwTagsList != null && !wwTagsList.isEmpty()) {
                for (WwTags wwTags : wwTagsList) {
                    WwCustomerTagsQuery wwCustomerTagsQuery = new WwCustomerTagsQuery();
                    wwCustomerTagsQuery.setTagId(wwTags.getId());
                    wwCustomerTagsQuery.setMerId(customerQuery.getMerId());
                    List<WwCustomerTags> wwCustomerTagsList = wwCustomerTagsMapper.getWwCustomerTags(wwCustomerTagsQuery);
                    if (wwCustomerTagsList != null && !wwCustomerTagsList.isEmpty()) {
                        for (WwCustomerTags wwCustomerTags : wwCustomerTagsList) {
                            customerIds.add(wwCustomerTags.getCustomerId());
                        }
                    }
                }
            } else {
                return new MyPageInfo<>(null);
            }
            if (customerIds != null && !customerIds.isEmpty()) {
                customerQuery.setCustomerIds(customerIds);
            } else {
                return new MyPageInfo<>(null);
            }

        }

        //获取对应标签的客户ID
        if (customerQuery.getTagId() != null) {
            WwCustomerTagsQuery wwCustomerTagsQuery = new WwCustomerTagsQuery();
            wwCustomerTagsQuery.setTagId(customerQuery.getTagId());
            wwCustomerTagsQuery.setMerId(customerQuery.getMerId());
            List<WwCustomerTags> wwCustomerTagsList = wwCustomerTagsMapper.getWwCustomerTags(wwCustomerTagsQuery);
            List<Long> customerIds = new ArrayList<>();
            if (wwCustomerTagsList != null && !wwCustomerTagsList.isEmpty()) {
                for (WwCustomerTags wwCustomerTags : wwCustomerTagsList) {
                    customerIds.add(wwCustomerTags.getCustomerId());
                }
            }
            if (customerIds != null && !customerIds.isEmpty()) {
                customerQuery.setCustomerIds(customerIds);
            } else {
                return new MyPageInfo<>(null);
            }
        }

        //传入机器人关键字段，先判断传入的是ID还是名字
        if (customerQuery.getDeviceUniqueKeyword() != null) {
            //id
            if (Tools.isNumeric(customerQuery.getDeviceUniqueKeyword())) {
                customerQuery.setDeviceUniqueId(Long.valueOf(customerQuery.getDeviceUniqueKeyword()));
            } else {
                //查询机器人
                WwDevice wwDevice = wwDeviceMapper.getByName(customerQuery.getDeviceUniqueKeyword(), customerQuery.getMerId());
                if (wwDevice != null) {
                    customerQuery.setDeviceUniqueId(wwDevice.getId());
                }
            }
        }

        //如果是子账号，只能查看自己账号所管理的 机器人
        if (customerQuery.getOperatorType() != null && customerQuery.getOperatorType() == 1) {
            if (customerQuery.getChildId() == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID为空");
            }
            List<MerchatChildDeviceRelation> merchatChildDeviceRelationList = merchatChildDeviceRelationMapper.selectByStaffId(customerQuery.getMerId(), customerQuery.getChildId());
            if (merchatChildDeviceRelationList == null || merchatChildDeviceRelationList.isEmpty()) {
                return new MyPageInfo<>(null);
            }
            List<Long> deviceUniqueIds = merchatChildDeviceRelationList.stream().map(MerchatChildDeviceRelation::getRobotId).distinct().collect(Collectors.toList());
            customerQuery.setChildOwnDeviceUniqueIds(deviceUniqueIds);
        }

        String orderBy = OrderByUtil.getOrderBy(customerQuery.getOrderByField(), customerQuery.isAsc());
        PageHelper.startPage(customerQuery.getCurrent(), customerQuery.getSize(), orderBy);
        List<WwCustomerVo> wwCustomerList = wwCustomerMapper.getCustomer(customerQuery);

        if (wwCustomerList == null && wwCustomerList.isEmpty()) {
            return new MyPageInfo<>(null);
        }

        //查询客户标签
        for (WwCustomerVo wwCustomerVo : wwCustomerList) {
            wwCustomerVo.setSceneDescByScene();
            List<String> wwtagNames = new ArrayList<>();
            List<String> personTagNames = new ArrayList<>();
            WwCustomerTagsQuery wwCustomerTagsQuery = new WwCustomerTagsQuery();
            wwCustomerTagsQuery.setCustomerId(wwCustomerVo.getId());
            wwCustomerTagsQuery.setMerId(wwCustomerVo.getMerId());
            List<WwCustomerTags> wwCustomerTagsList = wwCustomerTagsMapper.getWwCustomerTags(wwCustomerTagsQuery);
            if (wwCustomerTagsList != null && !wwCustomerTagsList.isEmpty()) {
                for (WwCustomerTags wwCustomerTags : wwCustomerTagsList) {
                    WwTags wwTags = wwTagsMapper.getById(wwCustomerTags.getTagId(), wwCustomerTags.getMerId());
                    if (wwTags != null) {
                        if (wwTags.getType() == 1) {
                            wwtagNames.add(wwTags.getTagName());
                        }
                        if (wwTags.getType() == 2) {
                            personTagNames.add(wwTags.getTagName());
                        }
                    }
                }
            }
            wwCustomerVo.setWwtagNames(wwtagNames);
            wwCustomerVo.setPersonTagNames(personTagNames);

            WwDevice wwDevice = wwDeviceMapper.getById(wwCustomerVo.getDeviceUniqueId(), wwCustomerVo.getMerId());
            if (wwDevice != null) {
                wwCustomerVo.setDeviceName(wwDevice.getDeviceName());
            }
        }

        MyPageInfo<WwCustomerVo> pageInfo = new MyPageInfo<>(wwCustomerList);
        return pageInfo;
    }

    @Override
    public Object getCustomerDetail(CustomerDto customerDto) {
        if (customerDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (customerDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        WwCustomer wwCustomer = wwCustomerMapper.getById(customerDto.getId(), customerDto.getMerId());
        if (wwCustomer == null) {
            return null;
        }
        WwCustomerVo wwCustomerVo = new WwCustomerVo();
        BeanUtil.copyProperties(wwCustomer, wwCustomerVo);
        wwCustomerVo.setSceneDescByScene();
        List<String> wwtagNames = new ArrayList<>();
        List<String> personTagNames = new ArrayList<>();
        List<Long> wwtagIds = new ArrayList<>();
        List<Long> personTagIds = new ArrayList<>();
        WwCustomerTagsQuery wwCustomerTagsQuery = new WwCustomerTagsQuery();
        wwCustomerTagsQuery.setCustomerId(wwCustomerVo.getId());
        wwCustomerTagsQuery.setMerId(wwCustomerVo.getMerId());
        List<WwCustomerTags> wwCustomerTagsList = wwCustomerTagsMapper.getWwCustomerTags(wwCustomerTagsQuery);
        if (wwCustomerTagsList != null && !wwCustomerTagsList.isEmpty()) {
            for (WwCustomerTags wwCustomerTags : wwCustomerTagsList) {
                try {
                    WwTags wwTags = wwTagsMapper.getById(wwCustomerTags.getTagId(), wwCustomerTags.getMerId());
                    if (wwTags.getType() == 1) {
                        wwtagIds.add(wwTags.getId());
                        wwtagNames.add(wwTags.getTagName());
                    }
                    if (wwTags.getType() == 2) {
                        personTagIds.add(wwTags.getId());
                        personTagNames.add(wwTags.getTagName());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        wwCustomerVo.setWwtagIds(wwtagIds);
        wwCustomerVo.setPersonTagIds(personTagIds);
        wwCustomerVo.setWwtagNames(wwtagNames);
        wwCustomerVo.setPersonTagNames(personTagNames);

        //自查，查看wxid有多少个
        CustomerQuery customerQuery = new CustomerQuery();
        customerQuery.setMerId(customerDto.getMerId());
        customerQuery.setWxid(wwCustomerVo.getWxid());
        List<WwCustomerVo> customerVoList = wwCustomerMapper.getCustomer(customerQuery);

        List<AddedDeviceVo> addedDeviceVoList = new ArrayList<>();
        if (customerVoList != null && !customerVoList.isEmpty()) {
            for (WwCustomerVo wwCustomerVo1 : customerVoList) {
                try {
                    WwDevice wwDevice = wwDeviceMapper.getById(wwCustomerVo1.getDeviceUniqueId(), wwCustomerVo1.getMerId());
                    AddedDeviceVo addedDeviceVo = new AddedDeviceVo();
                    addedDeviceVo.setId(wwDevice.getId());
                    addedDeviceVo.setDeviceName(wwDevice.getDeviceName());
                    addedDeviceVo.setHeadImgUrl(wwDevice.getHeadImgUrl());
                    addedDeviceVoList.add(addedDeviceVo);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        wwCustomerVo.setAddedDeviceVoList(addedDeviceVoList);
        return wwCustomerVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCustomer(CustomerDto customerDto) {

        if (customerDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (customerDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        WwCustomer wwCustomer = wwCustomerMapper.getById(customerDto.getId(), customerDto.getMerId());

        addCustomerBehavior(customerDto, wwCustomer);


        //修改备注同步到企业微信
        if (!StringUtils.isBlank(customerDto.getRemark()) && !customerDto.getRemark().equals(wwCustomer.getRemark())) {
            wwCustomer.setRemark(customerDto.getRemark());
            mqCustomerSetRemark(wwCustomer);
        }
        //备注改为空
        if (customerDto.getRemark() == null) {
            wwCustomer.setRemark("");
            mqCustomerSetRemark(wwCustomer);
        }

        wwCustomer.setNickname(customerDto.getNickname());
        wwCustomer.setMobile(customerDto.getMobile());
        wwCustomer.setDescription(customerDto.getDescription());
        wwCustomerMapper.update(wwCustomer);
//        wwCustomerMapper.updateWwCustomerMapper(wwCustomer);


        //修改企业标签

        //先删除企业标签
        WwCustomerTagsQuery wwCustomerTagsQuery = new WwCustomerTagsQuery();
        wwCustomerTagsQuery.setMerId(customerDto.getMerId());
        wwCustomerTagsQuery.setCustomerId(customerDto.getId());
        List<WwCustomerTags> wwCustomerTagsList = wwCustomerTagsMapper.getWwCustomerTags(wwCustomerTagsQuery);
        if (wwCustomerTagsList != null && !wwCustomerTagsList.isEmpty()) {
            for (WwCustomerTags wwCustomerTags : wwCustomerTagsList) {
                WwTags wwTags = wwTagsMapper.getById(wwCustomerTags.getTagId(), wwCustomerTags.getMerId());
                if (wwTags != null && wwTags.getType() == 1) {
                    wwCustomerTagsMapper.deleCustomerTags(wwCustomerTags.getId(), wwCustomerTags.getMerId());

                    mqDeleCustomerTagsRelation(wwCustomer.getId(), wwCustomer.getMerId(), 1, wwCustomerTags.getTagId());
                    /*if (StringUtils.isBlank(wwCustomer.getExternalUserid())) {
                    } else {
                        deleCustomerTagsRelation(wwCustomer.getId(), wwCustomer.getMerId(), Arrays.asList(wwTags.getExternalId()), Arrays.asList(wwTags.getCorpId()));
                    }*/
                }

            }
        }
        if (customerDto.getWwtagIds() != null && !customerDto.getWwtagIds().isEmpty()) {
            //再插入新企业标签
            for (Long wwTagId : customerDto.getWwtagIds()) {
                WwCustomerTags wwCustomerTags = new WwCustomerTags();
                wwCustomerTags.setMerId(customerDto.getMerId());
                wwCustomerTags.setCustomerId(customerDto.getId());
                wwCustomerTags.setTagId(wwTagId);
                WwTags wwTags = wwTagsMapper.getById(wwCustomerTags.getTagId(), wwCustomerTags.getMerId());

//                if (StringUtils.isBlank(wwTags.getCorpId()) || StringUtils.isBlank(wwTags.getExternalId())) {
//                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该标签企业id或企微开放平台id为空");
//                }
                wwCustomerTags.setTagIdStr(wwTags.getTagId());
                wwCustomerTagsMapper.addWwCustomerTags(wwCustomerTags);

                mqAddCustomerTagId(wwCustomer.getId(), wwCustomer.getMerId(), 1, wwTagId);
                /*if (StringUtils.isBlank(wwCustomer.getExternalUserid())) {
                } else {
                    addCustomerTagId(wwCustomer.getId(), wwCustomer.getMerId(), Collections.singletonList(wwTags));
                }*/
            }
        }

        //修改个人标签

        //先删除个人标签
        WwCustomerTagsQuery wwCustomerTagsQuery1 = new WwCustomerTagsQuery();
        wwCustomerTagsQuery1.setMerId(customerDto.getMerId());
        wwCustomerTagsQuery1.setCustomerId(customerDto.getId());
        List<WwCustomerTags> wwCustomerTagsList1 = wwCustomerTagsMapper.getWwCustomerTags(wwCustomerTagsQuery1);
        if (wwCustomerTagsList1 != null && !wwCustomerTagsList1.isEmpty()) {
            for (WwCustomerTags wwCustomerTags : wwCustomerTagsList1) {
                WwTags wwTags = wwTagsMapper.getById(wwCustomerTags.getTagId(), wwCustomerTags.getMerId());
                if (wwTags != null && wwTags.getType() == 2) {
                    wwCustomerTagsMapper.deleCustomerTags(wwCustomerTags.getId(), wwCustomerTags.getMerId());
                    mqDeleCustomerTagsRelation(wwCustomer.getId(), wwCustomer.getMerId(), 2, wwCustomerTags.getTagId());
                }

            }
        }
        if (customerDto.getPersonTagIds() != null && !customerDto.getPersonTagIds().isEmpty()) {
            //再插入新个人标签
            for (Long personTagId : customerDto.getPersonTagIds()) {
                WwCustomerTags wwCustomerTags = new WwCustomerTags();
                wwCustomerTags.setMerId(customerDto.getMerId());
                wwCustomerTags.setCustomerId(customerDto.getId());
                wwCustomerTags.setTagId(personTagId);
                WwTags wwTags = wwTagsMapper.getById(wwCustomerTags.getTagId(), wwCustomerTags.getMerId());
                wwCustomerTags.setTagIdStr(wwTags.getTagId());
                wwCustomerTagsMapper.addWwCustomerTags(wwCustomerTags);

                mqAddCustomerTagId(wwCustomer.getId(), wwCustomer.getMerId(), 2, personTagId);
            }
        }

    }

    private void addCustomerBehavior(CustomerDto customerDto, WwCustomer wwCustomer) {

        CustomerBehavior customerBehavior = new CustomerBehavior();
        int time = DateUtil.getTime();
        customerBehavior.setMerId(wwCustomer.getMerId());
        customerBehavior.setCustomerId(wwCustomer.getId());
        customerBehavior.setDeviceUniqueId(wwCustomer.getDeviceUniqueId());
        customerBehavior.setCreateTime(time);
        customerBehavior.setUpdateTime(time);

        if (!StringUtils.isBlank(customerDto.getRemark())) {
            if (StringUtils.isBlank(wwCustomer.getRemark())) {
                //新增备注
                customerBehavior.setId(IdWorker.getId());
                customerBehavior.setType(CustomerBehaviorTypeEnum.CUSTOMER_ADD_REMARK.getValue());
                customerBehavior.setMsg(CustomerBehaviorTypeEnum.CUSTOMER_ADD_REMARK.getDesc() + "【" + customerDto.getRemark() + "】");
                customerBehaviorMapper.insertSelective(customerBehavior);
            }
            if (!StringUtils.isBlank(wwCustomer.getRemark()) && !customerDto.getRemark().equals(wwCustomer.getRemark())) {
                //修改备至
                customerBehavior.setId(IdWorker.getId());
                customerBehavior.setType(CustomerBehaviorTypeEnum.CUSTOMER_UPDATE_REMARK.getValue());
                customerBehavior.setMsg(CustomerBehaviorTypeEnum.CUSTOMER_UPDATE_REMARK.getDesc() + "【" + customerDto.getRemark() + "】");
                customerBehaviorMapper.insertSelective(customerBehavior);
            }
        }
        if (!StringUtils.isBlank(customerDto.getNickname())) {
            if (StringUtils.isBlank(wwCustomer.getNickname())) {
                //新增称呼
                customerBehavior.setId(IdWorker.getId());
                customerBehavior.setType(CustomerBehaviorTypeEnum.CUSTOMER_ADD_USERNAME.getValue());
                customerBehavior.setMsg(CustomerBehaviorTypeEnum.CUSTOMER_ADD_USERNAME.getDesc() + "【" + customerDto.getNickname() + "】");
                customerBehaviorMapper.insertSelective(customerBehavior);
            }
            if (!StringUtils.isBlank(wwCustomer.getNickname()) && !customerDto.getNickname().equals(wwCustomer.getNickname())) {
                //修改称呼
                customerBehavior.setId(IdWorker.getId());
                customerBehavior.setType(CustomerBehaviorTypeEnum.CUSTOMER_UPDATE_USERNAME.getValue());
                customerBehavior.setMsg(CustomerBehaviorTypeEnum.CUSTOMER_UPDATE_USERNAME.getDesc() + "【" + customerDto.getNickname() + "】");
                customerBehaviorMapper.insertSelective(customerBehavior);
            }
        }
        if (!StringUtils.isBlank(customerDto.getMobile())) {
            //新增手机号
            if (StringUtils.isBlank(wwCustomer.getMobile())) {
                customerBehavior.setId(IdWorker.getId());
                customerBehavior.setType(CustomerBehaviorTypeEnum.CUSTOMER_ADD_MOBILE.getValue());
                customerBehavior.setMsg(CustomerBehaviorTypeEnum.CUSTOMER_ADD_MOBILE.getDesc() + "【" + customerDto.getMobile() + "】");
                customerBehaviorMapper.insertSelective(customerBehavior);
            }
            //修改手机
            if (!StringUtils.isBlank(wwCustomer.getMobile()) && !customerDto.getMobile().equals(wwCustomer.getMobile())) {
                customerBehavior.setId(IdWorker.getId());
                customerBehavior.setType(CustomerBehaviorTypeEnum.CUSTOMER_UPDATE_MOBILE.getValue());
                customerBehavior.setMsg(CustomerBehaviorTypeEnum.CUSTOMER_UPDATE_MOBILE.getDesc() + "【" + customerDto.getMobile() + "】");
                customerBehaviorMapper.insertSelective(customerBehavior);
            }
        }
        if (!StringUtils.isBlank(customerDto.getDescription())) {
            //新增备注
            if (StringUtils.isBlank(wwCustomer.getDescription())) {
                customerBehavior.setId(IdWorker.getId());
                customerBehavior.setType(CustomerBehaviorTypeEnum.CUSTOMER_ADD_DESCRIPTION.getValue());
                customerBehavior.setMsg(CustomerBehaviorTypeEnum.CUSTOMER_ADD_DESCRIPTION.getDesc() + "【" + customerDto.getDescription() + "】");
                customerBehaviorMapper.insertSelective(customerBehavior);
            }
            //修改备注
            if (!StringUtils.isBlank(wwCustomer.getDescription()) && !customerDto.getDescription().equals(wwCustomer.getDescription())) {
                customerBehavior.setId(IdWorker.getId());
                customerBehavior.setType(CustomerBehaviorTypeEnum.CUSTOMER_UPDATE_DESCRIPTION.getValue());
                customerBehavior.setMsg(CustomerBehaviorTypeEnum.CUSTOMER_UPDATE_DESCRIPTION.getDesc() + "【" + customerDto.getDescription() + "】");
                customerBehaviorMapper.insertSelective(customerBehavior);
            }
        }
    }

    @Override
    public Object getSceneDropDwon(BaseDto baseDto) {
        ArrayList<Map> arrayList = new ArrayList<>();
        for (WwFriendReqScene wwFriendReqScene : WwFriendReqScene.values()) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("label", wwFriendReqScene.getDesc());
            map.put("value", wwFriendReqScene.getValue());
            arrayList.add(map);
        }
        return arrayList;
    }

    @Override
    public Object getGenderDropDwon(BaseDto baseDto) {
        ArrayList<Map> arrayList = new ArrayList<>();
        for (GenderEnum genderEnum : GenderEnum.values()) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("label", genderEnum.getDesc());
            map.put("value", genderEnum.getId());
            arrayList.add(map);
        }
        return arrayList;
    }

    @Override
    public void batchUpdateCustomerRemake(BatchUpdateCustomerRemakeDto batchUpdateCustomerRemakeDto) {
        if (batchUpdateCustomerRemakeDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchUpdateCustomerRemakeDto.getSelectType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (batchUpdateCustomerRemakeDto.getUpdateType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (batchUpdateCustomerRemakeDto.getSelectType() == 0 && (batchUpdateCustomerRemakeDto.getCustomerIds() == null || batchUpdateCustomerRemakeDto.getCustomerIds().isEmpty())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        if (batchUpdateCustomerRemakeDto.getSelectType() == 0) {
            batchUpdateCustomerRemakeBySelect(batchUpdateCustomerRemakeDto);
        }
        if (batchUpdateCustomerRemakeDto.getSelectType() == 1) {
            batchUpdateCustomerRemakeAll(batchUpdateCustomerRemakeDto);
        }
    }


    private void batchUpdateCustomerRemakeBySelect(BatchUpdateCustomerRemakeDto batchUpdateCustomerRemakeDto) {
        if (batchUpdateCustomerRemakeDto.getUpdateType() == 0) {
            for (Long customerId : batchUpdateCustomerRemakeDto.getCustomerIds()) {
                try {
                    updateCustomerRemakeBySelectUnify(customerId, batchUpdateCustomerRemakeDto.getContent(), batchUpdateCustomerRemakeDto.getMerId());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        if (batchUpdateCustomerRemakeDto.getUpdateType() == 1) {
            for (Long customerId : batchUpdateCustomerRemakeDto.getCustomerIds()) {
                try {
                    updateCustomerRemakeBySelectKeywords(customerId, batchUpdateCustomerRemakeDto.getMerId(), batchUpdateCustomerRemakeDto.getKeyWords(), batchUpdateCustomerRemakeDto.getReplaceWords());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    @Async("taskExecutor")
    public void batchUpdateCustomerRemakeAll(BatchUpdateCustomerRemakeDto batchUpdateCustomerRemakeDto) {
        //查询出所有的客户
        CustomerQuery customerQuery = batchUpdateCustomerRemakeDto.getCustomerQuery();
        Long idStart = 0L;
        customerQuery.setMerId(batchUpdateCustomerRemakeDto.getMerId());
        customerQuery.setAsc(true);
        customerQuery.setCurrent(1);
        customerQuery.setSize(100);
        customerQuery.setOrderByField("id");
        customerQuery.setIdStart(idStart);
        String orderBy = OrderByUtil.getOrderBy(customerQuery.getOrderByField(), customerQuery.isAsc());
        PageHelper.startPage(customerQuery.getCurrent(), customerQuery.getSize(), orderBy);
        List<WwCustomerVo> customerVoList = wwCustomerMapper.getCustomer(customerQuery);
        while (customerVoList != null && !customerVoList.isEmpty()) {
            for (WwCustomerVo wwCustomerVo : customerVoList) {
                try {
                    if (wwCustomerVo.getId().longValue() > idStart.longValue()) {
                        idStart = wwCustomerVo.getId();
                    }
                    if (batchUpdateCustomerRemakeDto.getUpdateType() == 0) {
                        updateCustomerRemakeBySelectUnify(wwCustomerVo.getId(), batchUpdateCustomerRemakeDto.getContent(), batchUpdateCustomerRemakeDto.getMerId());
                    }

                    if (batchUpdateCustomerRemakeDto.getUpdateType() == 1) {
                        updateCustomerRemakeBySelectKeywords(wwCustomerVo.getId(), batchUpdateCustomerRemakeDto.getMerId(), batchUpdateCustomerRemakeDto.getKeyWords(), batchUpdateCustomerRemakeDto.getReplaceWords());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            customerQuery.setIdStart(idStart);
            PageHelper.startPage(customerQuery.getCurrent(), customerQuery.getSize(), orderBy);
            customerVoList = wwCustomerMapper.getCustomer(customerQuery);
        }
    }

    private void updateCustomerRemakeBySelectUnify(Long customerId, String content, Long merId) {
        WwCustomer wwCustomer = wwCustomerMapper.getById(customerId, merId);
        String newContent = Tools.getStr(content);
        newContent = newContent.replace("[微信昵称]", Tools.getStr(wwCustomer.getName())).replace("[性别]", Tools.getStr(GenderEnum.getById(wwCustomer.getGender()).getDesc())).replace("[添加日期]", Tools.getStr(DateUtil.convertTimestampToDate(wwCustomer.getCreateTime()))).replace("[当前备注]", Tools.getStr(wwCustomer.getRemark()));
        wwCustomer.setRemark(newContent);
        wwCustomerMapper.updateWwCustomerMapper(wwCustomer);
        //发送指令
        mqCustomerSetRemark(wwCustomer);
    }

    private void updateCustomerRemakeBySelectKeywords(Long customerId, Long merId, String keywords, String replaceWords) {
        WwCustomer wwCustomer = wwCustomerMapper.getById(customerId, merId);
        if (keywords != null && wwCustomer.getRemark().contains(keywords)) {
            String content = Tools.getStr(wwCustomer.getRemark());
            content = content.replaceAll(keywords, replaceWords);
            wwCustomer.setRemark(content);
            wwCustomerMapper.updateWwCustomerMapper(wwCustomer);

            //发送指令
            mqCustomerSetRemark(wwCustomer);
        }
    }


    @Override
    public void batchAddCustomerTag(BatchCustomerTagDto batchAddCustomerTagDto) {
        if (batchAddCustomerTagDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchAddCustomerTagDto.getSelectType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (batchAddCustomerTagDto.getSelectType() == 0 && (batchAddCustomerTagDto.getCustomerIds() == null || batchAddCustomerTagDto.getCustomerIds().isEmpty())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        if (batchAddCustomerTagDto.getSelectType() == 0) {
            batchAddCustomerTagBySelect(batchAddCustomerTagDto);
        }
        if (batchAddCustomerTagDto.getSelectType() == 1) {
            batchAddCustomerTagAll(batchAddCustomerTagDto);
        }

    }

    private void batchAddCustomerTagBySelect(BatchCustomerTagDto batchAddCustomerTagDto) {
        for (Long customerId : batchAddCustomerTagDto.getCustomerIds()) {
            try {
                addCustomerTagBySelect(customerId, batchAddCustomerTagDto.getMerId(), batchAddCustomerTagDto.getTagIds(), batchAddCustomerTagDto.getDeviceUniqueId(), batchAddCustomerTagDto.getType());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Async("taskExecutor")
    public void batchAddCustomerTagAll(BatchCustomerTagDto batchAddCustomerTagDto) {
        //查询出所有的客户
        CustomerQuery customerQuery = batchAddCustomerTagDto.getCustomerQuery();
        Long idStart = 0L;
        customerQuery.setMerId(batchAddCustomerTagDto.getMerId());
        customerQuery.setAsc(true);
        customerQuery.setCurrent(1);
        customerQuery.setSize(100);
        customerQuery.setOrderByField("id");
        customerQuery.setIdStart(idStart);
        List<WwCustomerVo> customerVoList = getCustomer(customerQuery).getRecords();
        while (customerVoList != null && !customerVoList.isEmpty()) {
            for (WwCustomerVo wwCustomerVo : customerVoList) {
                try {
                    if (wwCustomerVo.getId().longValue() > idStart.longValue()) {
                        idStart = wwCustomerVo.getId();
                    }
                    addCustomerTagBySelect(wwCustomerVo.getId(), batchAddCustomerTagDto.getMerId(), batchAddCustomerTagDto.getTagIds(), batchAddCustomerTagDto.getDeviceUniqueId(), batchAddCustomerTagDto.getType());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            customerQuery.setIdStart(idStart);
            customerVoList = getCustomer(customerQuery).getRecords();
        }
    }


    private void addCustomerTagBySelect(Long customerId, Long merId, List<Long> tagIds, Long deviceUniqueId, Integer type) {
        if (tagIds == null || tagIds.isEmpty()) {
            return;
        }
        //获取该客户所有的标签关系
        WwCustomerTagsQuery wwCustomerTagsQuery = new WwCustomerTagsQuery();
        wwCustomerTagsQuery.setMerId(merId);
        wwCustomerTagsQuery.setCustomerId(customerId);
        List<WwCustomerTags> wwCustomerTagsList = wwCustomerTagsMapper.getWwCustomerTags(wwCustomerTagsQuery);

        //获取已添加的标签ID
        List<Long> exsitTags = new ArrayList<>();
        wwCustomerTagsList.forEach(it -> exsitTags.add(it.getTagId()));

        WwCustomer wwCustomer = wwCustomerMapper.getById(customerId, merId);
        if (wwCustomer == null) {
            return;
        }

        //获取未添加的标签ID
        List<Long> collect = tagIds.stream().filter(it -> !exsitTags.contains(it)).collect(Collectors.toList());
        if (collect != null && !collect.isEmpty()) {

            for (Long tagId : collect) {
                WwTags wwTags = wwTagsMapper.getById(tagId, merId);
                WwCustomerTags wwCustomerTags = new WwCustomerTags();
                wwCustomerTags.setMerId(merId);
                wwCustomerTags.setTagId(tagId);
                wwCustomerTags.setCustomerId(customerId);
                wwCustomerTags.setTagIdStr(wwTags.getTagId());
                wwCustomerTagsMapper.addWwCustomerTags(wwCustomerTags);
        }
            /*if (type != null && type == 1 && !StringUtils.isBlank(wwCustomer.getExternalUserid())) {
            List<WwTags> wwTagsList = wwTagsMapper.getByIds(collect, merId);
            if (wwTagsList != null && !wwTagsList.isEmpty()) {

                addCustomerTagId(customerId, merId, wwTagsList);
            }
        }*/
        }
        tagIds.forEach(tagId -> {
            if (type != null && type == 2) {
                mqAddCustomerTagId(customerId, merId, type, tagId);
            }
            if (type != null && type == 1 /*&& StringUtils.isBlank(wwCustomer.getExternalUserid())*/) {
                mqAddCustomerTagId(customerId, merId, type, tagId);
            }
        });
    }

    /*public void addCustomerTagId(Long customerId, Long merId, List<WwTags> wwTagsList) {

        List<String> externalIds = wwTagsList.stream().map(WwTags::getExternalId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        List<String> corpIds = wwTagsList.stream().map(WwTags::getCorpId).filter(Objects::nonNull).distinct().collect(Collectors.toList());

        boolean allSame = corpIds.stream().distinct().limit(2).count() <= 1;
        if (!allSame) {
            return;
        }
        if (externalIds == null && externalIds.isEmpty()) {
            return;
        }
        WwCustomer wwCustomer = wwCustomerMapper.getById(customerId, merId);
        if (wwCustomer == null) {
            return;
        }
        WwDevice wwDevice = wwDeviceMapper.getById(wwCustomer.getDeviceUniqueId(), merId);
        if (wwDevice == null) {
            return;
        }
        WwCorp wwCorp = wwCorpMapper.getByCorpId(String.valueOf(corpIds.get(0)), merId);
        if (wwCorp == null || com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(wwCorp.getEntId()) || com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(wwCorp.getEntSecret())) {
            return;
        }
        WwTagMarkDTO wwTagMarkDTO = new WwTagMarkDTO();
        wwTagMarkDTO.setUserid(wwDevice.getAcctId());
        wwTagMarkDTO.setExternal_userid(wwCustomer.getExternalUserid());
        wwTagMarkDTO.setAdd_tag(externalIds);

        String accessToken = (String) redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.QYWX_TOKEN.getKey(), wwCorp.getEntId()));
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(accessToken)) {
            accessToken = WwApiUtil.getAccessToken(wwCorp.getEntId(), wwCorp.getEntSecret());
//            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.QYWX_TOKEN.getKey(), wwCorp.getEntId()), accessToken);
        }
        WwApiUtil.markTag(accessToken, wwTagMarkDTO);

        for (WwTags wwTags : wwTagsList) {
            MicaCustomerAddTagMsg micaCustomerAddTagMsg = new MicaCustomerAddTagMsg();
            micaCustomerAddTagMsg.setId(wwTags.getId());
            micaCustomerAddTagMsg.setWxid(wwCustomer.getWxid());
            micaCustomerAddTagMsg.setType(1);
            micaCustomerAddTagMsg.setExternalId(wwTags.getExternalId());
            MicaTransDto micaTransDto = MicaTransDto.newInstance(micaCustomerAddTagMsg, MicaMsgType.CONSOLE_TO_SERVER_CUSTOMER_ADD_TAG);
            micaTransDto.setMerId(merId);
            micaTransDto.setDeviceId(wwDevice.getDeviceId());
            micaTransDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
            sendMsgProducer.pushMsg(micaTransDto, MicaTopics.CONSOLE_TO_SERVER_TOPIC);
        }
    }*/

    private void mqAddCustomerTagId(Long customerId, Long merId, Integer type, Long tagId) {
        //获取个微推送过来的标签ID
        WwTags wwtags = wwTagsMapper.getById(tagId, merId);
        //获取客户的wxId
        WwCustomer wwCustomer = wwCustomerMapper.getById(customerId, merId);
        WwDevice wwDevice = wwDeviceMapper.getById(wwCustomer.getDeviceUniqueId(), merId);

        MicaTriggerBatchMarkLabelMsg micaTriggerChangeLabelMsg = new MicaTriggerBatchMarkLabelMsg();
        micaTriggerChangeLabelMsg.setAddWxIds(Arrays.asList(wwCustomer.getWxid()));
        micaTriggerChangeLabelMsg.setLabelId(wwtags.getTagId());
        micaTriggerChangeLabelMsg.setIsCorp(type == 1);
        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerChangeLabelMsg, MicaTriggerType.TRIGGER_BATCH_MARK_LABEL);
        micaTriggerDto.setMerId(merId);
        micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);


        MicaCustomerAddTagMsg micaCustomerAddTagMsg = new MicaCustomerAddTagMsg();
        micaCustomerAddTagMsg.setTagId(wwtags.getTagId());
        micaCustomerAddTagMsg.setWxid(wwCustomer.getWxid());
        micaCustomerAddTagMsg.setType(type);
        MicaTransDto micaTransDto = MicaTransDto.newInstance(micaCustomerAddTagMsg, MicaMsgType.CONSOLE_TO_SERVER_CUSTOMER_ADD_TAG);
        micaTransDto.setMerId(merId);
        micaTransDto.setDeviceId(wwDevice.getDeviceId());
        micaTransDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTransDto, MicaTopics.CONSOLE_TO_SERVER_TOPIC);

    }


    @Override
    public void batchDeleCustomerTag(BatchCustomerTagDto batchCustomerTagDto) {
        if (batchCustomerTagDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchCustomerTagDto.getSelectType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (batchCustomerTagDto.getSelectType() == 0 && (batchCustomerTagDto.getCustomerIds() == null || batchCustomerTagDto.getCustomerIds().isEmpty())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        if (batchCustomerTagDto.getSelectType() == 0) {
            batchDeleCustomerTagBySelect(batchCustomerTagDto);
        }
        if (batchCustomerTagDto.getSelectType() == 1) {
            batchDeleCustomerTagAll(batchCustomerTagDto);

        }
    }

    private void batchDeleCustomerTagBySelect(BatchCustomerTagDto batchCustomerTagDto) {

        if (batchCustomerTagDto.getType() != null && batchCustomerTagDto.getType() == 2) {
            Long merId = batchCustomerTagDto.getMerId();
            List<Long> tagIds = batchCustomerTagDto.getTagIds();
            //
            List<WwTags> wwTags = wwTagsMapper.getByIds(tagIds, merId);
            //
            List<WwCustomer> customers = wwCustomerMapper.getByIds(batchCustomerTagDto.getCustomerIds(), merId);
            //
            if (ObjectUtils.isEmpty(wwTags) || ObjectUtils.isEmpty(customers)) {
                throw new BusinessException("批量删除标签失败: 客户或标签不存在");
            }
            //
            Map<Long, List<WwCustomer>> deviceCustomerMap = customers.stream().collect(Collectors.groupingBy(WwCustomer::getDeviceUniqueId));
            //
            for (WwTags wwTag : wwTags) {
                //
                for (Map.Entry<Long, List<WwCustomer>> deviceCustomerEntry : deviceCustomerMap.entrySet()) {
                    //
                    WwDevice wwDevice = wwDeviceMapper.getById(deviceCustomerEntry.getKey(), merId);
                    if (ObjectUtils.isEmpty(wwDevice)) {
                        log.error("批量删除标签, 客户对应的机器人未找到: {}", deviceCustomerEntry.getKey());
                        continue;
                    }
                    List<String> delWxIds = deviceCustomerEntry.getValue().stream().map(WwCustomer::getWxid).distinct().collect(Collectors.toList());

                    MicaTriggerBatchMarkLabelMsg micaTriggerChangeLabelMsg = new MicaTriggerBatchMarkLabelMsg();
                    micaTriggerChangeLabelMsg.setDelWxIds(delWxIds);
                    micaTriggerChangeLabelMsg.setLabelId(wwTag.getTagId());
                    micaTriggerChangeLabelMsg.setIsCorp(batchCustomerTagDto.getType() == 1);

                    MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerChangeLabelMsg, MicaTriggerType.TRIGGER_BATCH_MARK_LABEL, item -> {
                        item.setMerId(merId);
                        item.setDeviceId(wwDevice.getDeviceId());
                        item.setDeviceType(9);
                    });
                    sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
                }
                //
                int count = wwCustomerTagsMapper.deleteByTagIdAndCustomerIds(merId, wwTag.getId(), batchCustomerTagDto.getCustomerIds());
                log.info("批量移除标签数量: tagId: {}, 数量: {}", wwTag.getId(), count);
            }
        }

        if (batchCustomerTagDto.getType() != null && batchCustomerTagDto.getType() == 1) {
            for (Long customerId : batchCustomerTagDto.getCustomerIds()) {
                try {
                    deleCustomerTagBySelect(customerId, batchCustomerTagDto.getMerId(), batchCustomerTagDto.getTagIds(), batchCustomerTagDto.getDeviceUniqueId(), batchCustomerTagDto.getType());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Async("taskExecutor")
    public void batchDeleCustomerTagAll(BatchCustomerTagDto batchCustomerTagDto) {
        //查询出所有的客户
        CustomerQuery customerQuery = batchCustomerTagDto.getCustomerQuery();
        Long idStart = 0L;
        customerQuery.setMerId(batchCustomerTagDto.getMerId());
        customerQuery.setAsc(true);
        customerQuery.setCurrent(1);
        customerQuery.setSize(100);
        customerQuery.setOrderByField("id");
        customerQuery.setIdStart(idStart);
        List<WwCustomerVo> customerVoList = getCustomer(customerQuery).getRecords();
        while (customerVoList != null && !customerVoList.isEmpty()) {
            for (WwCustomerVo wwCustomerVo : customerVoList) {
                try {
                    if (wwCustomerVo.getId().longValue() > idStart.longValue()) {
                        idStart = wwCustomerVo.getId();
                    }
                    deleCustomerTagBySelect(wwCustomerVo.getId(), batchCustomerTagDto.getMerId(), batchCustomerTagDto.getTagIds(), batchCustomerTagDto.getDeviceUniqueId(), batchCustomerTagDto.getType());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            customerQuery.setIdStart(idStart);
            customerVoList = getCustomer(customerQuery).getRecords();
        }
    }

    @Deprecated
    private void deleCustomerTagBySelect(Long customerId, Long merId, List<Long> tagIds, Long deviceUniqueId, Integer type) {
        if (tagIds == null || tagIds.isEmpty()) {
            return;
        }
        WwCustomer wwCustomer = wwCustomerMapper.getById(customerId, merId);
        if (wwCustomer == null) {
            return;
        }

        List<String> externalIds = new ArrayList<>();
        List<String> corpIds = new ArrayList<>();
        WwCustomerTagsQuery wwCustomerTagsQuery = new WwCustomerTagsQuery();
        wwCustomerTagsQuery.setMerId(merId);
        wwCustomerTagsQuery.setCustomerId(customerId);
        List<WwCustomerTags> wwCustomerTagsList = wwCustomerTagsMapper.getWwCustomerTags(wwCustomerTagsQuery);
        for (WwCustomerTags wwCustomerTags : wwCustomerTagsList) {
            try {
                if (tagIds.contains(wwCustomerTags.getTagId())) {

                    wwCustomerTagsMapper.deleCustomerTags(wwCustomerTags.getId(), wwCustomerTags.getMerId());

                    if (type != null && type == 2) {
                        mqDeleCustomerTagsRelation(customerId, merId, type, wwCustomerTags.getTagId());
                    }

                    if (type != null && type == 1 /*&& StringUtils.isBlank(wwCustomer.getExternalUserid())*/) {
                        mqDeleCustomerTagsRelation(customerId, merId, type, wwCustomerTags.getTagId());
                    }

                    /*if (type != null && type == 1 && !StringUtils.isBlank(wwCustomer.getExternalUserid())) {
                        WwTags wwTags = wwTagsMapper.getById(wwCustomerTags.getTagId(), merId);
                        if (wwTags != null && !StringUtils.isBlank(wwTags.getExternalId()) && wwTags.getCorpId() != null) {
                            externalIds.add(wwTags.getExternalId());
                            corpIds.add(wwTags.getCorpId());
                        }
                    }*/

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /*if (type != null && type == 1 && !externalIds.isEmpty() && !corpIds.isEmpty() && !StringUtils.isBlank(wwCustomer.getExternalUserid())) {
            deleCustomerTagsRelation(customerId, merId, externalIds, corpIds);
        }*/
    }

    /*public void deleCustomerTagsRelation(Long customerId, Long merId, List<String> externalIds, List<String> corpIds) {
        boolean allSame = corpIds.stream().distinct().limit(2).count() <= 1;
        if (!allSame) {
            return;
        }
        if (externalIds == null && externalIds.isEmpty()) {
            return;
        }
        WwCustomer wwCustomer = wwCustomerMapper.getById(customerId, merId);
        if (wwCustomer == null) {
            return;
        }
        WwDevice wwDevice = wwDeviceMapper.getById(wwCustomer.getDeviceUniqueId(), merId);
        if (wwDevice == null) {
            return;
        }
        WwCorp wwCorp = wwCorpMapper.getByCorpId(String.valueOf(corpIds.get(0)), merId);
        if (wwCorp == null || com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(wwCorp.getEntId()) || com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(wwCorp.getEntSecret())) {
            return;
        }
        WwTagMarkDTO wwTagMarkDTO = new WwTagMarkDTO();
        wwTagMarkDTO.setUserid(wwDevice.getAcctId());
        wwTagMarkDTO.setExternal_userid(wwCustomer.getExternalUserid());
        wwTagMarkDTO.setRemove_tag(externalIds.stream().distinct().collect(Collectors.toList()));

        String accessToken = (String) redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.QYWX_TOKEN.getKey(), wwCorp.getEntId()));
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(accessToken)) {
            accessToken = WwApiUtil.getAccessToken(wwCorp.getEntId(), wwCorp.getEntSecret());
//            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.QYWX_TOKEN.getKey(), wwCorp.getEntId()), accessToken);
        }
        WwApiUtil.markTag(accessToken, wwTagMarkDTO);
    }*/

    private void mqDeleCustomerTagsRelation(Long customerId, Long merId, Integer type, Long tagId) {
        //获取推送过来的标签ID
        WwTags wwtags = wwTagsMapper.getById(tagId, merId);
        //获取客户的wxId
        WwCustomer wwCustomer = wwCustomerMapper.getById(customerId, merId);
        WwDevice wwDevice = wwDeviceMapper.getById(wwCustomer.getDeviceUniqueId(), merId);
        MicaTriggerBatchMarkLabelMsg micaTriggerChangeLabelMsg = new MicaTriggerBatchMarkLabelMsg();
        micaTriggerChangeLabelMsg.setDelWxIds(Arrays.asList(wwCustomer.getWxid()));
        micaTriggerChangeLabelMsg.setLabelId(wwtags.getTagId());
        micaTriggerChangeLabelMsg.setIsCorp(type == 1);
        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerChangeLabelMsg, MicaTriggerType.TRIGGER_BATCH_MARK_LABEL);
        micaTriggerDto.setMerId(merId);
        micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTags(TagDto tagDto) {
        if (tagDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (tagDto.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (tagDto.getType() == null || tagDto.getType() == 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (tagDto.getTagNames() == null || tagDto.getTagNames().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (StringUtils.isBlank(tagDto.getFirstLevelTagName())) {

            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        //查询是否有同一分组名
        CustomerTagQuery customerTagQuery = new CustomerTagQuery();
        customerTagQuery.setMerId(tagDto.getMerId());
        customerTagQuery.setType(2);
        customerTagQuery.setPid(0L);
        customerTagQuery.setTagName(tagDto.getFirstLevelTagName());
        customerTagQuery.setDeviceUniqueId(tagDto.getDeviceUniqueId());
        List<WwTags> customerTag = wwTagsMapper.getCustomerTag(customerTagQuery);
        if (customerTag != null && !customerTag.isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "存在同名的标签组");
        }

        //查询是否有同名的标签名
        for (String tagName : tagDto.getTagNames()) {
            CustomerTagQuery tagQuery = new CustomerTagQuery();
            tagQuery.setMerId(tagDto.getMerId());
            tagQuery.setType(2);
            tagQuery.setIfChild(1);
            tagQuery.setTagName(tagName);
            tagQuery.setDeviceUniqueId(tagDto.getDeviceUniqueId());
            List<WwTags> wwTagsList = wwTagsMapper.getCustomerTag(tagQuery);
            if (wwTagsList != null && !wwTagsList.isEmpty()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "存在同名的标签");
            }
        }


        tagDto.setStatus(0);
        //设置一级标签
        int time = DateUtil.getTime();
        WwTags wwTags = new WwTags();
        long id = IdWorker.getId();
        wwTags.setId(id);
        wwTags.setMerId(tagDto.getMerId());
        wwTags.setType(tagDto.getType());
        wwTags.setTagName(tagDto.getFirstLevelTagName());
        wwTags.setPid(0L);
        wwTags.setStatus(1);
        wwTags.setDeviceUniqueId(tagDto.getDeviceUniqueId());
        wwTags.setCreateTime(time);
        wwTags.setUpdateTime(time);
        wwTagsMapper.insertWwTags(wwTags);

        //设置二级标签
        for (String tagName : tagDto.getTagNames()) {
            int nowTime = DateUtil.getTime();
            WwTags tags = new WwTags();
            long tagId = IdWorker.getId();
            tags.setId(tagId);
            tags.setMerId(tagDto.getMerId());
            tags.setType(tagDto.getType());
            tags.setTagName(tagName);
            tags.setPid(id);
            tags.setStatus(tagDto.getStatus());
            tags.setDeviceUniqueId(tagDto.getDeviceUniqueId());
            tags.setCreateTime(nowTime);
            tags.setUpdateTime(nowTime);
            wwTagsMapper.insertWwTags(tags);

            mqAddTagId(tagName, tagId, tagDto.getMerId(), tagDto.getDeviceUniqueId());
        }
    }

    @Override
    public void batchMoveCustomerTag(BatchCustomerTagDto batchCustomerTagDto) {
        if (batchCustomerTagDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchCustomerTagDto.getSelectType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (batchCustomerTagDto.getSelectType() == 0 && (batchCustomerTagDto.getCustomerIds() == null || batchCustomerTagDto.getCustomerIds().isEmpty())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        if (batchCustomerTagDto.getSelectType() == 0) {
            batchMoveCustomerTagBySelect(batchCustomerTagDto);
        }
        if (batchCustomerTagDto.getSelectType() == 1) {
            batchMoveCustomerTagAll(batchCustomerTagDto);

        }
    }

    private void batchMoveCustomerTagBySelect(BatchCustomerTagDto batchCustomerTagDto) {
        for (Long customerId : batchCustomerTagDto.getCustomerIds()) {
            try {
                MoveCustomerTagBySelect(customerId, batchCustomerTagDto.getMerId(), batchCustomerTagDto.getTagIds(), batchCustomerTagDto.getDeviceUniqueId(), batchCustomerTagDto.getType(), batchCustomerTagDto.getMoveDelTagIds());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Async("taskExecutor")
    public void batchMoveCustomerTagAll(BatchCustomerTagDto batchCustomerTagDto) {
        //查询出所有的客户
        CustomerQuery customerQuery = batchCustomerTagDto.getCustomerQuery();
        Long idStart = 0L;
        customerQuery.setMerId(batchCustomerTagDto.getMerId());
        customerQuery.setAsc(true);
        customerQuery.setCurrent(1);
        customerQuery.setSize(100);
        customerQuery.setOrderByField("id");
        customerQuery.setIdStart(idStart);
        List<WwCustomerVo> customerVoList = getCustomer(customerQuery).getRecords();
        while (customerVoList != null && !customerVoList.isEmpty()) {
            for (WwCustomerVo wwCustomerVo : customerVoList) {
                try {
                    if (wwCustomerVo.getId().longValue() > idStart.longValue()) {
                        idStart = wwCustomerVo.getId();
                    }
                    MoveCustomerTagBySelect(wwCustomerVo.getId(), batchCustomerTagDto.getMerId(), batchCustomerTagDto.getTagIds(), batchCustomerTagDto.getDeviceUniqueId(), batchCustomerTagDto.getType(), batchCustomerTagDto.getMoveDelTagIds());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            customerQuery.setIdStart(idStart);
            customerVoList = getCustomer(customerQuery).getRecords();
        }

    }

    private void MoveCustomerTagBySelect(Long customerId, Long merId, List<Long> tagIds, Long deviceUniqueId, Integer type, List<Long> moveDelTagIds) {
        //获取所有的标签
        WwCustomerTagsQuery wwCustomerTagsQuery = new WwCustomerTagsQuery();
        wwCustomerTagsQuery.setCustomerId(customerId);
        wwCustomerTagsQuery.setMerId(merId);
        List<WwCustomerTags> wwCustomerTagsList = wwCustomerTagsMapper.getWwCustomerTags(wwCustomerTagsQuery);
        //删除原标签
        if (wwCustomerTagsList != null && !wwCustomerTagsList.isEmpty()) {
            List<Long> deleTagIds = new ArrayList<>();
            wwCustomerTagsList.forEach(it -> {
                if (moveDelTagIds.contains(it.getTagId())) {
                    deleTagIds.add(it.getTagId());
                }
            });

            if (!deleTagIds.isEmpty()) {
                deleCustomerTagBySelect(customerId, merId, deleTagIds, deviceUniqueId, type);
            }

        }
        //新增标签
        addCustomerTagBySelect(customerId, merId, tagIds, deviceUniqueId, type);
    }


    @Override
    @Async("taskExecutor")
    public void addCustomerToTags(AddCustomerToTagsDto addCustomerToTagsDto) {
//        CustomerTagDto customerTagDto=new CustomerTagDto();
//        BeanUtil.copyProperties(addCustomerToTagsDto,customerTagDto);
//        Long tagId = addCustomerPersonTag(customerTagDto);
//        if(tagId!=null){
        BatchCustomerTagDto batchCustomerTagDto = new BatchCustomerTagDto();
        batchCustomerTagDto.setMerId(addCustomerToTagsDto.getMerId());
        batchCustomerTagDto.setSelectType(0);
        batchCustomerTagDto.setCustomerIds(addCustomerToTagsDto.getCustomerIds());
        batchCustomerTagDto.setTagIds(Arrays.asList(addCustomerToTagsDto.getId()));
        if (addCustomerToTagsDto.getType() == 2 && addCustomerToTagsDto.getDeviceUniqueId() != null) {
            batchCustomerTagDto.setDeviceUniqueId(addCustomerToTagsDto.getDeviceUniqueId());
        }
        batchCustomerTagDto.setType(addCustomerToTagsDto.getType());
        batchAddCustomerTag(batchCustomerTagDto);
    }
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleCustomerPersonTAgs(DeleCustomerPersonTAgsDto deleCustomerPersonTAgsDto) {
        if (deleCustomerPersonTAgsDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (deleCustomerPersonTAgsDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        WwTags wwTags = wwTagsMapper.getById(deleCustomerPersonTAgsDto.getId(), deleCustomerPersonTAgsDto.getMerId());
        if (wwTags != null) {
            ArrayList<Long> TagIds = new ArrayList<>();
            //如果是父标签，查询出子标签并删除
            if (wwTags.getPid() != null && wwTags.getPid() == 0) {
                CustomerTagQuery customerTagQuery = new CustomerTagQuery();
                customerTagQuery.setPid(wwTags.getId());
                customerTagQuery.setMerId(wwTags.getMerId());
                List<WwTags> customerTag = wwTagsMapper.getCustomerTag(customerTagQuery);
                for (WwTags wwTags1 : customerTag) {
                    TagIds.add(wwTags1.getId());
                    wwTagsMapper.deleWwTagsById(wwTags1.getId(), wwTags1.getMerId());
                    mqDeleTagId(wwTags1, wwTags1.getId(), wwTags1.getMerId(), wwTags1.getDeviceUniqueId());
                }
                //再删除标签组
                wwTagsMapper.deleWwTagsById(deleCustomerPersonTAgsDto.getId(), deleCustomerPersonTAgsDto.getMerId());
//             mqDeleTagId(wwTags, wwTags.getId(), wwTags.getMerId(), wwTags.getDeviceUniqueId());
            } else {
                //删除标签
                TagIds.add(deleCustomerPersonTAgsDto.getId());
                int i = wwTagsMapper.deleWwTagsById(deleCustomerPersonTAgsDto.getId(), deleCustomerPersonTAgsDto.getMerId());
                mqDeleTagId(wwTags, wwTags.getId(), wwTags.getMerId(), wwTags.getDeviceUniqueId());
            }


            //删除标签关系
            BatchCustomerTagDto batchCustomerTagDto = new BatchCustomerTagDto();
            batchCustomerTagDto.setMerId(deleCustomerPersonTAgsDto.getMerId());
            batchCustomerTagDto.setSelectType(1);
            batchCustomerTagDto.setType(2);
            batchCustomerTagDto.setTagIds(TagIds);
            batchCustomerTagDto.setDeviceUniqueId(deleCustomerPersonTAgsDto.getDeviceUniqueId());
            batchCustomerTagDto.setCustomerQuery(new CustomerQuery());
            batchDeleCustomerTag(batchCustomerTagDto);

        }
    }

    @Override
    public void updateCustomerPersonTAgs(CustomerTagDto customerTagDto) {
        if (customerTagDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (customerTagDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (StringUtils.isBlank(customerTagDto.getTagName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        //查询所有的标签，查看是否有重复标签
        CustomerTagQuery customerTagQuery = new CustomerTagQuery();
        customerTagQuery.setMerId(customerTagDto.getMerId());
        customerTagQuery.setType(2);
        List<WwTags> customerTag = wwTagsMapper.getCustomerTag(customerTagQuery);
        if (customerTag != null && !customerTag.isEmpty()) {
            List<String> customerTagNames = new ArrayList<>();
            customerTag.forEach(it -> customerTagNames.add(it.getTagName()));
            if (customerTagNames.contains(customerTagDto.getTagName())) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "重复的标签名");
            }
        }

        WwTags wwTags = wwTagsMapper.getById(customerTagDto.getId(), customerTagDto.getMerId());
        if (wwTags != null) {
            wwTags.setTagName(customerTagDto.getTagName());
            wwTagsMapper.updateWwTags(wwTags);

            //发送mq指令修改标签名
            WwDevice wwDevice = wwDeviceMapper.getById(wwTags.getDeviceUniqueId(), wwTags.getMerId());
            MicaTriggerChangeLabelMsg micaTriggerChangeLabelMsg = new MicaTriggerChangeLabelMsg();
            micaTriggerChangeLabelMsg.setMessageId(wwTags.getId());
            micaTriggerChangeLabelMsg.setLabelId(wwTags.getTagId());
            micaTriggerChangeLabelMsg.setLabelName(wwTags.getTagName());
            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerChangeLabelMsg, MicaTriggerType.TRIGGER_CHANGE_LABEL);
            micaTriggerDto.setMerId(wwDevice.getMerId());
            micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
            micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
        }

    }

    @Override
    public void batchDeleCustomer(BatchDeleCustomerDto batchDeleCustomerDto) {
        if (batchDeleCustomerDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchDeleCustomerDto.getSelectType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (batchDeleCustomerDto.getSelectType() == 0 && (batchDeleCustomerDto.getIds() == null || batchDeleCustomerDto.getIds().isEmpty())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        if (batchDeleCustomerDto.getSelectType() == 0) {
            batchDeleCustomerBySelect(batchDeleCustomerDto);
        }
        if (batchDeleCustomerDto.getSelectType() == 1) {
            batchDeleCustomerAll(batchDeleCustomerDto);
        }
    }


    private void batchDeleCustomerBySelect(BatchDeleCustomerDto batchDeleCustomerDto) {
        for (Long customerId : batchDeleCustomerDto.getIds()) {
            try {
                batchDeleCustomerDto.setCustomerId(customerId);
                customerService.deleCustomer(batchDeleCustomerDto);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void batchDeleCustomerAll(BatchDeleCustomerDto batchDeleCustomerDto) {

        //查询出所有的客户
        CustomerQuery customerQuery = batchDeleCustomerDto.getCustomerQuery();
        Long idStart = 0L;
        customerQuery.setMerId(batchDeleCustomerDto.getMerId());
        customerQuery.setAsc(true);
        customerQuery.setCurrent(1);
        customerQuery.setSize(100);
        customerQuery.setOrderByField("id");
        customerQuery.setIdStart(idStart);
        List<WwCustomerVo> customerVoList = getCustomer(customerQuery).getRecords();
        while (customerVoList != null && !customerVoList.isEmpty()) {
            for (WwCustomerVo wwCustomerVo : customerVoList) {
                try {
                    if (wwCustomerVo.getId().longValue() > idStart.longValue()) {
                        idStart = wwCustomerVo.getId();
                    }
                    batchDeleCustomerDto.setCustomerId(wwCustomerVo.getId());
                    customerService.deleCustomer(batchDeleCustomerDto);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            customerQuery.setIdStart(idStart);
            customerVoList = getCustomer(customerQuery).getRecords();
        }
    }

    @Override
    public Object getCustomerSelectPage(GetCustomerSelectPageQuery query) {
        if (query.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        //
        List<Long> includeWwCustomerIds = new ArrayList<>();
        boolean hasIncludeWwCustomerIds = false;
        List<Long> excludeWwCustomerIds = new ArrayList<>();
        boolean hasExcludeWwCustomerIds = false;

        //
        List<Long> includePersonCustomerIds = new ArrayList<>();
        boolean hasIncludePersonCustomerIds = false;
        List<Long> excludePersonCustomerIds = new ArrayList<>();
        boolean hasExcludePersonCustomerIds = false;

        if (Objects.nonNull(query.getWwtagIdType())) {
            if (!Objects.equals(query.getWwtagIdType(), 2)) {
                hasIncludeWwCustomerIds = true;
                //先获取标签ID
                List<WwTags> wwTagsList = queryWwTags(true, query);
                //
                if (ObjectUtils.isEmpty(wwTagsList)) {
                    return new MyPageInfo<>(null);
                }
                List<Long> tagIds1 = wwTagsList.stream().map(WwTags::getId).distinct().collect(Collectors.toList());
                //
                includeWwCustomerIds = wwCustomerTagsMapper.selectListOfCustomerIdsByTagId(query.getMerId(), tagIds1);
            } else if (Objects.equals(query.getWwtagIdType(), 2)) {
                hasExcludeWwCustomerIds = true;
                //
                excludeWwCustomerIds = wwCustomerTagsMapper.selectListOfCustomerIdsByTagType(query.getMerId(), 1);
            }
        }

        if (Objects.nonNull(query.getPersonTagType())) {
            if (!Objects.equals(query.getPersonTagType(), 2)) {
                hasIncludePersonCustomerIds = true;
                //先获取标签ID
                List<WwTags> wwTagsList = queryWwTags(false, query);
                //
                if (ObjectUtils.isEmpty(wwTagsList)) {
                    return new MyPageInfo<>(null);
                }
                List<Long> tagIds1 = wwTagsList.stream().map(WwTags::getId).distinct().collect(Collectors.toList());
                //
                includePersonCustomerIds = wwCustomerTagsMapper.selectListOfCustomerIdsByTagId(query.getMerId(), tagIds1);
            } else if (Objects.equals(query.getPersonTagType(), 2)) {
                hasExcludePersonCustomerIds = true;
                excludePersonCustomerIds = wwCustomerTagsMapper.selectListOfCustomerIdsByTagType(query.getMerId(), 2);
            }
        }

        // 企业个人都包含 - 求并集
        if (hasIncludeWwCustomerIds && hasIncludePersonCustomerIds) {
            Collection<Long> customerIds = CollUtil.intersection(
                    ObjectUtils.defaultIfNull(includeWwCustomerIds, Lists.newArrayList()),
                    ObjectUtils.defaultIfNull(includePersonCustomerIds, Lists.newArrayList())
            );
            query.setCustomerIds(new ArrayList<>(customerIds));
        }
        // 企业包含,个人不包含 企业-个人
        else if (hasIncludeWwCustomerIds && hasExcludePersonCustomerIds) {
            if (ObjectUtils.isEmpty(includeWwCustomerIds)) {
                return new MyPageInfo<>(null);
            }
            if (ObjectUtils.isNotEmpty(excludePersonCustomerIds)) {
                includeWwCustomerIds.removeAll(excludePersonCustomerIds);
            }
            query.setCustomerIds(includeWwCustomerIds);
        }
        // 企业不包含, 个人包含 个人-企业
        else if (hasExcludeWwCustomerIds && hasIncludePersonCustomerIds) {
            if (ObjectUtils.isEmpty(includePersonCustomerIds)) {
                return new MyPageInfo<>(null);
            }
            if (ObjectUtils.isNotEmpty(excludeWwCustomerIds)) {
                includePersonCustomerIds.removeAll(excludeWwCustomerIds);
            }
            query.setCustomerIds(includePersonCustomerIds);
        }
        // 企业个人都不包含 - 求和
        else if (hasExcludeWwCustomerIds && hasExcludePersonCustomerIds) {
            if (ObjectUtils.isEmpty(excludeWwCustomerIds) && ObjectUtils.isEmpty(excludePersonCustomerIds)) {
                return new MyPageInfo<>(null);
            }
            excludeWwCustomerIds.addAll(excludePersonCustomerIds);
            query.setNotInCustomerIds(excludeWwCustomerIds);
        } else if (hasIncludePersonCustomerIds) {
            query.setCustomerIds(includePersonCustomerIds);
        } else if (hasIncludeWwCustomerIds) {
            query.setCustomerIds(includeWwCustomerIds);
        } else if (hasExcludePersonCustomerIds) {
            query.setNotInCustomerIds(excludePersonCustomerIds);
        } else if (hasExcludeWwCustomerIds) {
            query.setNotInCustomerIds(excludeWwCustomerIds);
        }

        String orderBy = OrderByUtil.getOrderBy(query.getOrderByField(), query.isAsc());
        PageHelper.startPage(query.getCurrent(), query.getSize(), orderBy);
        List<WwCustomerVo> wwDeviceVoList = wwCustomerMapper.getCustomerSelectPage(query);
        if (wwDeviceVoList != null && !wwDeviceVoList.isEmpty()) {
            List<String> wxIds = wwDeviceVoList.stream().map(WwCustomerVo::getWxid).distinct().collect(Collectors.toList());
            List<Long> deviceUniqueIds = wwDeviceVoList.stream().map(WwCustomerVo::getDeviceUniqueId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            Map<Long, WwDevice> wwDevicesCache = wwDeviceMapper.selectByIds(query.getMerId(), deviceUniqueIds).stream().collect(Collectors.toMap(WwDevice::getId, Function.identity()));

            List<String> whitelists = whiteListMapper.selectListOfWxIdByWxIds(query.getMerId(), wxIds);
            List<String> blacklists = blackListMapper.selectListOfWxIdByWxIds(query.getMerId(), wxIds);

            for (WwCustomerVo wwCustomerVo : wwDeviceVoList) {
                try {
                    //判断是否在白名单中
                    if (whitelists.contains(wwCustomerVo.getWxid())) {
                        wwCustomerVo.setInWhiteList(true);
                    }
                    //判断是否在黑名单中
                    if (blacklists.contains(wwCustomerVo.getWxid())) {
                        wwCustomerVo.setInBlackList(true);
                    }

                    if (wwDevicesCache.containsKey(wwCustomerVo.getDeviceUniqueId())) {
                        WwDevice wwDevice = wwDevicesCache.get(wwCustomerVo.getDeviceUniqueId());
                        wwCustomerVo.setDeviceName(wwDevice.getDeviceName());
                        wwCustomerVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        MyPageInfo<WwCustomerVo> pageInfo = new MyPageInfo<>(wwDeviceVoList);
        return pageInfo;

    }

    private List<WwTags> queryWwTags(boolean ww, GetCustomerSelectPageQuery query) {
        CustomerTagQuery customerTagQuery = new CustomerTagQuery();
        customerTagQuery.setType(ww ? 1 : 2);
        customerTagQuery.setMerId(query.getMerId());
        customerTagQuery.setStatus(1);
        customerTagQuery.setTagNames(ww ? query.getWwTagIdNames() : query.getPersonTagNames());
        customerTagQuery.setTagType(ww ? query.getWwtagIdType() : query.getPersonTagType());
        return wwTagsMapper.getCustomerTag(customerTagQuery);
    }

    @Override
    public void syncCustomerTag(SyncCustomerTagDto syncCustomerTagDto) {
        log.info("syncCustomerTag: {}", JSON.toJSONString(syncCustomerTagDto));
        if (syncCustomerTagDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (syncCustomerTagDto.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        String key = String.format(CacheKey.SYNC_CUSTOMER_TAG_CACHE, syncCustomerTagDto.getMerId());
        Boolean status = (Boolean) redisTemplate.opsForValue().get(key);
        if (status != null && status) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "正在同步，请" + DateUtil.convertSecondsToHourMinuteSecond(Math.toIntExact(redisTemplate.getExpire(key, TimeUnit.SECONDS))) + "后再试");
        } else {
            redisTemplate.opsForValue().set(key, true, 300, TimeUnit.SECONDS);
        }

        if (syncCustomerTagDto.getType() == 1) {
            log.info("触发企业同步标签");
            syncWwCustomerTag(syncCustomerTagDto);
        }
        if (syncCustomerTagDto.getType() == 2) {
            log.info("触发个人同步标签");
            syncPersonCustomerTagV1(syncCustomerTagDto);
        }

    }

    @Override
    @Transactional
    public void syncCustomerTagV1(SyncCustomerTagV1Dto syncCustomerTagDto, CorpApplication corpApplication) {
        Long merId = syncCustomerTagDto.getMerId();
        Long corpId = syncCustomerTagDto.getCorpId();
        String cacheKey = String.format(RedisCacheKeyEnum.PUSH_OPEN_QYTAG.getKey(), merId, corpId);
        if (Boolean.FALSE.equals(redisTemplate.opsForValue().setIfAbsent(cacheKey, 1))) {
            throw new BusinessException("同步正在处理中, 请稍后重试");
        }

        try {

            //
            WwCorpVO wwCorpVO = wwCorpService.getAndCheck(merId, corpId);

            String accessToken = WwApiUtil.getAppAccessToken(corpApplication.getAuthCorpId(), corpApplication.getPermanentCode());

            WwTagGetResultDTO wwTagGetResultDTO;
            try {
                wwTagGetResultDTO = WwApiUtil.listTag(accessToken, null, null);
            } catch (Exception e) {
                throw new BusinessException("获取企业标签失败: 授权信息错误, 请检查配置!");
            }
            log.info("获取的企微标签: {}", JSON.toJSONString(wwTagGetResultDTO));

            List<WwTags> groupTags = wwTagsMapper.selectByType1AndPid0CorpId(merId, String.valueOf(corpId));

            for (WwTagGetResultDTO.TagGroup tagGroup : wwTagGetResultDTO.getTag_group()) {
                String groupName = tagGroup.getGroup_name();
                String groupId = tagGroup.getGroup_id();
                WwTags parent = wwTagsMapper.selectByType1AndPid0TagIdAndCorpId(merId, groupId, wwCorpVO.getCorpId());
                if (Objects.nonNull(parent)) {
                    WwTags finalParent = parent;
                    groupTags.removeIf(i -> Objects.equals(i.getId(), finalParent.getId()));
                    //
                    if (!StringUtils.equals(parent.getTagName(), groupName)) {
                        WwTags update = new WwTags();
                        update.setId(parent.getId());
                        update.setTagName(groupName);
                        if (StringUtils.isNotBlank(parent.getTagId())) {
                            update.setStatus(1);
                        }
                        update.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
                        wwTagsMapper.updateWwTags(update);
                    }
                } else {
                    List<WwTags> wwTagsList = wwTagsMapper.selectByType1AndPid0TagNameAndCorpId(merId, groupName, wwCorpVO.getCorpId());
                    if (ObjectUtils.isEmpty(wwTagsList)) {
                        parent = new WwTags();
                        parent.setId(IdUtil.getSnowflakeNextId());
                        parent.setMerId(merId);
                        parent.setTagName(tagGroup.getGroup_name());
                        parent.setExternalId(groupId);
                        parent.setType(1);
                        parent.setPid(0L);
                        parent.setStatus(0);
                        parent.setCorpId(wwCorpVO.getCorpId());
                        parent.setCreateTime((int) (System.currentTimeMillis() / 1000L));
                        parent.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
                        wwTagsMapper.insertWwTags(parent);
                    } else {
                        if (wwTagsList.size() > 1) {
                            log.error("当前标签组: {}, 存在重复数据", groupName);
                            continue;
                        }
                        parent = wwTagsList.get(0);
                        WwTags update = new WwTags();
                        update.setId(parent.getId());
                        update.setExternalId(groupId);
                        if (StringUtils.isNotBlank(parent.getTagId())) {
                            update.setStatus(1);
                        }
                        update.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
                        wwTagsMapper.updateWwTags(update);
                        WwTags finalParent = parent;
                        groupTags.removeIf(i -> Objects.equals(i.getId(), finalParent.getId()));
                    }
                }


                if (ObjectUtils.isEmpty(tagGroup.getTag())) {
                    wwTagsMapper.deleteByParentId(merId, parent.getId());
                    continue;
                }
                List<WwTags> existsChildTags = wwTagsMapper.selectByType1PidCorpId(merId, parent.getId(), corpId);

                for (WwTagGetResultDTO.Tag tag : tagGroup.getTag()) {
                    WwTags childTag = wwTagsMapper.selectByType1ExternalId(merId, tag.getId());
                    if (Objects.nonNull(childTag)) {
                        if (!StringUtils.equals(childTag.getTagName(), tag.getName())) {
                            WwTags update = new WwTags();
                            update.setId(childTag.getId());
                            update.setTagName(tag.getName());
                            update.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
                            wwTagsMapper.updateWwTags(update);
                        }
                        existsChildTags.removeIf(item -> Objects.equals(item.getId(), childTag.getId()));
                        continue;
                    }
                    WwTags childNameTag = wwTagsMapper.selectByType1AndPidCorpIdAndTagName(merId, wwCorpVO.getCorpId(), tag.getName(), parent.getId());
                    if (Objects.isNull(childNameTag)) {
                        WwTags insert = new WwTags();

                        insert.setId(IdUtil.getSnowflakeNextId());
                        insert.setMerId(merId);
                        insert.setTagName(tag.getName());
                        insert.setCorpId(wwCorpVO.getCorpId());
                        insert.setType(1);
                        insert.setPid(parent.getId());
                        insert.setStatus(0);
                        insert.setExternalId(tag.getId());
                        insert.setCreateTime((int) (System.currentTimeMillis() / 1000L));
                        insert.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
                        wwTagsMapper.insertWwTags(insert);
                    } else {
                        WwTags childUpdate = new WwTags();
                        childUpdate.setId(childNameTag.getId());

                        childUpdate.setExternalId(tag.getId());
                        childUpdate.setPid(parent.getId());
                        if (StringUtils.isNotBlank(childNameTag.getTagId())) {
                            childUpdate.setStatus(1);
                        }
                        childUpdate.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
                        wwTagsMapper.updateWwTags(childUpdate);
                        existsChildTags.removeIf(item -> Objects.equals(item.getId(), childUpdate.getId()));
                    }
                }
                log.info("existsChildTags: {}", existsChildTags);
                if (ObjectUtils.isNotEmpty(existsChildTags)) {
                    existsChildTags.forEach(item -> wwTagsMapper.deleWwTagsById(item.getId(), merId));
                }
            }
            log.info("groupTags: {}", groupTags);
            if (ObjectUtils.isNotEmpty(groupTags)) {
                groupTags.forEach(item -> {
                    wwTagsMapper.deleWwTagsById(item.getId(), merId);
                    wwTagsMapper.deleteByParentId(merId, item.getId());
                });
            }

            TimeUnit.SECONDS.sleep(2);
            // 同步手机标签
            SyncCustomerTagDto syncCustomerTagDto1 = new SyncCustomerTagDto();
            syncCustomerTagDto1.setMerId(merId);
            syncWwCustomerTag(syncCustomerTagDto1);
        } catch (Exception e) {
            log.error("同步企业标签失败", e);
            throw new BusinessException(e.getMessage());
        } finally {
            redisTemplate.delete(cacheKey);
        }
    }

    @Override
    public void batchSyncPersonTag(BatchSyncPersonDto batchSyncPersonDto) {

        if (batchSyncPersonDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchSyncPersonDto.getDeviceUniqueIds() == null || batchSyncPersonDto.getDeviceUniqueIds().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        for (Long deviceUniqueId : batchSyncPersonDto.getDeviceUniqueIds()) {
            try {
                SyncTagJob syncTagJob = syncTagJobMapper.getByDeviceUniqueId(deviceUniqueId, batchSyncPersonDto.getMerId());
                //新增
                if (syncTagJob == null) {
                    addSyncTagJob(deviceUniqueId, batchSyncPersonDto.getMerId());
                } else {
                    //修改
                    //先判断任务是否未执行或正在执行中
                    if (syncTagJob.getStatus() == 0 || syncTagJob.getStatus() == 1) {
                        continue;
                    }
                    updateSyncTagJob(syncTagJob);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public void addSyncTagJob(Long deviceUniqueId, Long merId) {
        SyncTagJob syncTagJob = new SyncTagJob();
        syncTagJob.setMerId(merId);
        syncTagJob.setDeviceUniqueId(deviceUniqueId);
        syncTagJob.setStatus(0);
        syncTagJob.setJobCreateTime(DateUtil.getTime());
        syncTagJobMapper.add(syncTagJob);
    }

    public void updateSyncTagJob(SyncTagJob syncTagJob) {
        syncTagJob.setStatus(0);
        syncTagJob.setJobCreateTime(DateUtil.getTime());
        syncTagJob.setStartTime(null);
        syncTagJobMapper.update(syncTagJob);
    }


    @Override
    public Object getBatchSyncPersonTagList(BatchSyncPersonTagQuery batchSyncPersonTagQuery) {
        if (batchSyncPersonTagQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        //获取机器人ID
        if (!StringUtils.isBlank(batchSyncPersonTagQuery.getKeyword())) {
            WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
            wwDeviceQuery.setMerId(batchSyncPersonTagQuery.getMerId());
            wwDeviceQuery.setKeyword(batchSyncPersonTagQuery.getKeyword());
            List<WwDeviceVo> wwDeviceVoList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
            if (wwDeviceVoList == null || wwDeviceVoList.isEmpty()) {
                return new MyPageInfo<>(null);
            }
            List<Long> deviceUniqueIds = wwDeviceVoList.stream().map(WwDeviceVo::getId).distinct().collect(Collectors.toList());
            batchSyncPersonTagQuery.setDeviceUniqueIds(deviceUniqueIds);
        }
        String orderBy = OrderByUtil.getOrderBy(batchSyncPersonTagQuery.getOrderByField(), batchSyncPersonTagQuery.isAsc());
        PageHelper.startPage(batchSyncPersonTagQuery.getCurrent(), batchSyncPersonTagQuery.getSize(), orderBy);

        List<SyncTagJobVo> syncTagJobVoList = syncTagJobMapper.getBatchSyncPersonTagList(batchSyncPersonTagQuery);

        if (syncTagJobVoList != null && !syncTagJobVoList.isEmpty()) {
            for (SyncTagJobVo syncTagJobVo : syncTagJobVoList) {
                try {
                    WwDevice wwDevice = wwDeviceMapper.getById(syncTagJobVo.getDeviceUniqueId(), syncTagJobVo.getMerId());
                    if (wwDevice != null) {
                        syncTagJobVo.setDeviceName(wwDevice.getDeviceName());
                        syncTagJobVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return new MyPageInfo<>(syncTagJobVoList);
    }


    @Override
    public void delSyncPersonTag(DelSyncPersonTagDto delSyncPersonTagDto) {
        if (delSyncPersonTagDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (delSyncPersonTagDto.getIds() == null || delSyncPersonTagDto.getIds().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        for (Long id : delSyncPersonTagDto.getIds()) {
            try {
                syncTagJobMapper.delById(id, delSyncPersonTagDto.getMerId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    @Async("taskExecutor")
    public void excuteSyncPersonTag(BaseDto baseDto) {
        BatchSyncPersonTagQuery batchSyncPersonTagQuery = new BatchSyncPersonTagQuery();
        Long idStart = 0L;
        batchSyncPersonTagQuery.setMerId(baseDto.getMerId());
        batchSyncPersonTagQuery.setAsc(true);
        batchSyncPersonTagQuery.setCurrent(1);
        batchSyncPersonTagQuery.setSize(50);
        batchSyncPersonTagQuery.setOrderByField("id");
        batchSyncPersonTagQuery.setIdStart(idStart);
        batchSyncPersonTagQuery.setStatus(1);
        String orderBy = OrderByUtil.getOrderBy(batchSyncPersonTagQuery.getOrderByField(), batchSyncPersonTagQuery.isAsc());
        PageHelper.startPage(batchSyncPersonTagQuery.getCurrent(), batchSyncPersonTagQuery.getSize(), orderBy);

        List<SyncTagJobVo> syncTagJobVoList = syncTagJobMapper.getBatchSyncPersonTagList(batchSyncPersonTagQuery);
        while (syncTagJobVoList != null && !syncTagJobVoList.isEmpty()) {
            int nowTime = DateUtil.getTime();
            for (SyncTagJobVo syncTagJobVo : syncTagJobVoList) {
                try {
                    if (syncTagJobVo.getId().longValue() > idStart.longValue()) {
                        idStart = syncTagJobVo.getId();
                    }

                    if (nowTime - syncTagJobVo.getStartTime() > 600) {
                        SyncTagJob syncTagJob = syncTagJobMapper.getById(syncTagJobVo.getId(), syncTagJobVo.getMerId());
                        if (syncTagJob != null) {
                            syncTagJob.setStatus(3);
                            syncTagJobMapper.update(syncTagJob);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            batchSyncPersonTagQuery.setIdStart(idStart);
            PageHelper.startPage(batchSyncPersonTagQuery.getCurrent(), batchSyncPersonTagQuery.getSize(), orderBy);
            syncTagJobVoList = syncTagJobMapper.getBatchSyncPersonTagList(batchSyncPersonTagQuery);
        }


        SyncTagJob syncTagJob = syncTagJobMapper.getUnSyncTagTask(baseDto.getMerId());
        if (syncTagJob != null) {

            WwDevice wwDevice = wwDeviceMapper.getById(syncTagJob.getDeviceUniqueId(), syncTagJob.getMerId());
            MicaTriggerPushLabelMsg micaTriggerPushLabelMsg = new MicaTriggerPushLabelMsg();
            micaTriggerPushLabelMsg.setMessageId(IdWorker.getId());
            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerPushLabelMsg, MicaTriggerType.TRIGGER_PUSH_LABEL);
            micaTriggerDto.setMerId(wwDevice.getMerId());
            micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
            micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);


            syncTagJob.setStatus(1);
            syncTagJob.setStartTime(DateUtil.getTime());
            syncTagJobMapper.update(syncTagJob);
        }

    }

    @Override
    @Transactional
    public void syncToRemote(@MerId Long merId, Long id, CorpApplication corpApplication) {

        WwCorpVO corpVO = wwCorpService.getAndCheck(merId, id);

        List<WwTags> groupTags = wwTagsMapper.selectByType1AndPid0CorpId(merId, String.valueOf(corpVO.getCorpId()));
        if (ObjectUtils.isEmpty(groupTags)) {
            return;
        }

        String appAccessToken = WwApiUtil.getAppAccessToken(corpApplication.getAuthCorpId(), corpApplication.getPermanentCode());
        //
        WwTagGetResultDTO tagGetResult = WwApiUtil.listTag(appAccessToken, null, null);
        List<WwTagGetResultDTO.TagGroup> remoteTagGroupList = tagGetResult.getTag_group();

        for (WwTags groupTag : groupTags) {
            WwTagGetResultDTO.TagGroup findGroup = CollUtil.findOne(remoteTagGroupList, i -> i.getGroup_name().equals(groupTag.getTagName()) || i.getGroup_id().equals(groupTag.getExternalId()));
            boolean create = false;

            WwTagAddDTO groupTagAdd = new WwTagAddDTO();

            if (Objects.nonNull(findGroup)) {
                groupTag.setExternalId(findGroup.getGroup_id());
                groupTag.setTagName(findGroup.getGroup_name());
                groupTagAdd.setGroup_id(groupTag.getExternalId());
            } else {
                create = true;
                groupTagAdd.setGroup_name(groupTag.getTagName());
            }

            List<WwTags> childTags = wwTagsMapper.selectByType1Pid(merId, groupTag.getId());
            if (ObjectUtils.isEmpty(childTags)) {
                continue;
            }

            if (!create) {
                for (WwTagGetResultDTO.Tag tag : findGroup.getTag()) {
                    WwTags findChildTag = CollUtil.findOne(childTags, i -> Objects.equals(tag.getName(), i.getTagName()) || Objects.equals(tag.getId(), i.getExternalId()));
                    if (Objects.nonNull(findChildTag)) {
                        childTags.remove(findChildTag);
                        if (!Objects.equals(findChildTag.getExternalId(), tag.getId())) {
                            findChildTag.setExternalId(tag.getId());
                            wwTagsMapper.updateWwTags(findChildTag);
                        }
                    }
                }
            }
            if (ObjectUtils.isEmpty(childTags)) {
                continue;
            }
            //
            groupTagAdd.setTag(
                    childTags.stream().map(WwTags::getTagName).distinct().map(WwTagAddDTO.Tag::new).collect(Collectors.toList())
            );
            try {
                WwTagAddResultDTO tagAddResult = WwApiUtil.addTag(appAccessToken, groupTagAdd);
                //
                WwTagAddResultDTO.TagGroup addResult = tagAddResult.getTag_group();
                if (create) {
                    groupTag.setExternalId(addResult.getGroup_id());
                    groupTag.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
                    wwTagsMapper.updateWwTags(groupTag);
                }
                //
                for (WwTagAddResultDTO.Tag tagItem : addResult.getTag()) {
                    WwTags find = CollUtil.findOne(childTags, i -> Objects.equals(tagItem.getName(), i.getTagName()));
                    if (Objects.nonNull(find)) {
                        find.setExternalId(tagItem.getId());
                        wwTagsMapper.updateWwTags(find);
                    }
                }
            } catch (Exception e) {
                log.error("创建标签异常", e);
            }
        }
    }

    @Override
    public Page<WwCustomer> pageFromChat(@MerId Long merId, RPullCustomerMsg content) {

        Page<WwCustomer> page = new Page<>(content.getCurrent(), content.getSize());

        List<WwCustomer> customerList = wwCustomerMapper.pageByCondition(page, content);
        if (ObjectUtils.isEmpty(customerList)) {
            return page;
        }
        page.setRecords(customerList);
        return page;
    }

    @Async("taskExecutor")
    public void syncPersonCustomerTag(SyncCustomerTagDto syncCustomerTagDto) {
        CustomerTagQuery customerTagQuery = new CustomerTagQuery();
        customerTagQuery.setMerId(syncCustomerTagDto.getMerId());
        List<WwTags> customerTag = wwTagsMapper.getCustomerTag(customerTagQuery);
        List<Long> deviceUniqueIds = new ArrayList<>();
        if (customerTag != null && !customerTag.isEmpty()) {
            deviceUniqueIds = customerTag.stream().filter(it -> it.getDeviceUniqueId() != null).map(WwTags::getDeviceUniqueId).distinct().collect(Collectors.toList());
        }
        if (deviceUniqueIds != null && !deviceUniqueIds.isEmpty()) {
            for (Long deviceUniqueId : deviceUniqueIds) {
                syncCustomerTagDto.setDeviceUniqueId(deviceUniqueId);
                syncWwCustomerTagByDeviceUniqueId(syncCustomerTagDto);
            }
        }
    }

    @Async("taskExecutor")
    public void syncPersonCustomerTagV1(SyncCustomerTagDto syncCustomerTagDto) {
        CustomerTagQuery customerTagQuery = new CustomerTagQuery();
        customerTagQuery.setMerId(syncCustomerTagDto.getMerId());

        List<Long> deviceUniqueIds;
        if (Objects.equals(syncCustomerTagDto.getOperatorType(), 0)) {
            List<WwDevice> devices = wwDeviceMapper.selectByMerId(syncCustomerTagDto.getMerId());
            if (ObjectUtils.isEmpty(devices)) {
                return;
            }
            deviceUniqueIds = devices.stream().map(WwDevice::getId).distinct().collect(Collectors.toList());
        } else {
            List<MerchatChildDeviceRelation> merchatChildDeviceRelations = merchatChildDeviceRelationMapper.selectByStaffId(syncCustomerTagDto.getMerId(), syncCustomerTagDto.getChildId());
            if (ObjectUtils.isEmpty(merchatChildDeviceRelations)) {
                log.info("员工未关联机器人");
                return;
            }
            deviceUniqueIds = merchatChildDeviceRelations.stream().map(MerchatChildDeviceRelation::getRobotId).distinct().collect(Collectors.toList());
        }

        if (ObjectUtils.isNotEmpty(deviceUniqueIds)) {
            for (Long deviceUniqueId : deviceUniqueIds) {
                syncWwCustomerTagByDeviceUniqueId(deviceUniqueId, syncCustomerTagDto.getMerId());
            }
        }
    }

    @Async("taskExecutor")
    public void syncWwCustomerTag(SyncCustomerTagDto syncCustomerTagDto) {
        //查询出所有的机器人
        WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
        wwDeviceQuery.setMerId(syncCustomerTagDto.getMerId());
        List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
        List<Long> deviceUniqueIds = new ArrayList<>();
        if (wwDeviceList != null && !wwDeviceList.isEmpty()) {
            List<String> corpIds = wwDeviceList.stream().map(WwDeviceVo::getCorpId).distinct().collect(Collectors.toList());
            if (!corpIds.isEmpty()) {
                for (String corpId : corpIds) {
                    WwDeviceQuery query = new WwDeviceQuery();
                    query.setMerId(syncCustomerTagDto.getMerId());
                    query.setCorpId(corpId);
                    List<WwDeviceVo> wwDeviceVoList = wwDeviceMapper.getWwDeviceList(query);
                    if (!wwDeviceList.isEmpty()) {
                        for (WwDeviceVo wwDeviceVo : wwDeviceVoList) {
                            Integer lastHeatBeatTime = (Integer) redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WW_DEVICE_LAST_HEAT_BEAT_TIME.getKey(), wwDeviceVo.getDeviceId()));
                            if (lastHeatBeatTime != null && (DateUtil.getTime() - lastHeatBeatTime) <= 300) {
                                deviceUniqueIds.add(wwDeviceVo.getId());
                                break;
                            }
                        }
                    }
                }
            }

//            List<WwDeviceVo> groupDeviceList = wwDeviceList.stream().collect(Collectors.toMap(WwDeviceVo::getCorpId, Function.identity(), (existing, replacement) -> existing)).values().stream().collect(Collectors.toList());
//          deviceUniqueIds = groupDeviceList.stream().filter(Objects::nonNull).map(WwDeviceVo::getId).distinct().collect(Collectors.toList());
        }
        if (deviceUniqueIds != null && !deviceUniqueIds.isEmpty()) {
            for (Long deviceUniqueId : deviceUniqueIds) {
                syncCustomerTagDto.setDeviceUniqueId(deviceUniqueId);
                syncWwCustomerTagByDeviceUniqueId(deviceUniqueId, syncCustomerTagDto.getMerId());
            }
        }
    }

    private void syncWwCustomerTagByDeviceUniqueId(SyncCustomerTagDto syncCustomerTagDto) {
        WwDevice wwDevice = wwDeviceMapper.getById(syncCustomerTagDto.getDeviceUniqueId(), syncCustomerTagDto.getMerId());
        MicaTriggerPushLabelMsg micaTriggerPushLabelMsg = new MicaTriggerPushLabelMsg();
        micaTriggerPushLabelMsg.setMessageId(IdWorker.getId());
        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerPushLabelMsg, MicaTriggerType.TRIGGER_PUSH_LABEL);
        micaTriggerDto.setMerId(wwDevice.getMerId());
        micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
    }

    private void syncWwCustomerTagByDeviceUniqueId(Long deviceUniqueId, Long merId) {
        WwDevice wwDevice = wwDeviceMapper.getById(deviceUniqueId, merId);
        MicaTriggerPushLabelMsg micaTriggerPushLabelMsg = new MicaTriggerPushLabelMsg();
        micaTriggerPushLabelMsg.setMessageId(IdWorker.getId());
        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerPushLabelMsg, MicaTriggerType.TRIGGER_PUSH_LABEL);
        micaTriggerDto.setMerId(wwDevice.getMerId());
        micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
    }

    private void mqCustomerSetRemark(WwCustomer wwCustomer) {
        WwDevice wwDevice = wwDeviceMapper.getById(wwCustomer.getDeviceUniqueId(), wwCustomer.getMerId());
        MicaTriggerCustomerSetRemarkMsg micaTriggerCustomerSetRemarkMsg = new MicaTriggerCustomerSetRemarkMsg();
        micaTriggerCustomerSetRemarkMsg.setRemark(wwCustomer.getRemark());
        micaTriggerCustomerSetRemarkMsg.setWxid(wwCustomer.getWxid());
        micaTriggerCustomerSetRemarkMsg.setMessageId(wwCustomer.getId());
        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerCustomerSetRemarkMsg, MicaTriggerType.TRIGGER_SET_REMARK);
        micaTriggerDto.setMerId(wwDevice.getMerId());
        micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
    }

    @Override
    public void syncCustomer(SyncCustomerDto syncCustomerDto) {
        if (syncCustomerDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (syncCustomerDto.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        //设置评率
        String key = String.format(RedisCacheKeyEnum.SYNC_CUSTOMER_GAP.getKey(), syncCustomerDto.getMerId());
        if (redisTemplate.hasKey(key)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "正在同步，请" + DateUtil.convertSecondsToHourMinuteSecond(Math.toIntExact(redisTemplate.getExpire(key, TimeUnit.SECONDS))) + "后再试");
        } else {
            redisTemplate.opsForValue().set(key, true, 300, TimeUnit.SECONDS);
        }


        WwDevice wwDevice = wwDeviceMapper.getById(syncCustomerDto.getDeviceUniqueId(), syncCustomerDto.getMerId());
        MicaTriggerContactPushMsg micaTriggerContactPushMsg = new MicaTriggerContactPushMsg();
        micaTriggerContactPushMsg.setMessageId(IdWorker.getId());
        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerContactPushMsg, MicaTriggerType.TRIGGER_CONTACT_PUSH);
        micaTriggerDto.setMerId(wwDevice.getMerId());
        micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

        //设置更新通讯录时间
        wwDevice.setLastSyncCustomerTime(DateUtil.getTime());
        wwDeviceMapper.updateWwDevice(wwDevice);
    }



    @Override
    public void batchSyncCustomer(BatchSyncCustomerDto batchSyncCustomerDto) {
        if (batchSyncCustomerDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchSyncCustomerDto.getDeviceUniqueIds() == null || batchSyncCustomerDto.getDeviceUniqueIds().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        for (Long deviceUniqueId : batchSyncCustomerDto.getDeviceUniqueIds()) {
            try {
                //先查看是否有该机器人的同步通讯录任务记录
                SyncCustomerJob syncCustomerJob = syncCustomerJobMapper.getByDeviceUniqueId(deviceUniqueId, batchSyncCustomerDto.getMerId());
                //新增
                if (syncCustomerJob == null) {
                    addSyncCustomerJob(deviceUniqueId, batchSyncCustomerDto.getMerId());
                } else {
                    //修改
                    //先判断任务是否未执行或正在执行中
                    if (syncCustomerJob.getStatus() == 0 || syncCustomerJob.getStatus() == 1) {
                        continue;
                    }
                    updateSyncCustomerJob(syncCustomerJob);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public void addSyncCustomerJob(Long deviceUniqueId, Long merId) {
        SyncCustomerJob syncCustomerJob = new SyncCustomerJob();
        syncCustomerJob.setMerId(merId);
        syncCustomerJob.setDeviceUniqueId(deviceUniqueId);
        syncCustomerJob.setStatus(0);
        syncCustomerJob.setJobCreateTime(DateUtil.getTime());
        syncCustomerJobMapper.add(syncCustomerJob);
    }

    public void updateSyncCustomerJob(SyncCustomerJob syncCustomerJob) {
        syncCustomerJob.setStatus(0);
        syncCustomerJob.setJobCreateTime(DateUtil.getTime());
        syncCustomerJob.setStartTime(null);
        syncCustomerJobMapper.update(syncCustomerJob);
    }


    @Override
    public Object getSyncCustomerList(SyncCustomerQuery syncCustomerQuery) {
        if (syncCustomerQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        //获取机器人ID
        if (!StringUtils.isBlank(syncCustomerQuery.getKeyword())) {
            WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
            wwDeviceQuery.setMerId(syncCustomerQuery.getMerId());
            wwDeviceQuery.setKeyword(syncCustomerQuery.getKeyword());
            List<WwDeviceVo> wwDeviceVoList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
            if (wwDeviceVoList == null || wwDeviceVoList.isEmpty()) {
                return new MyPageInfo<>(null);
            }
            List<Long> deviceUniqueIds = wwDeviceVoList.stream().map(WwDeviceVo::getId).distinct().collect(Collectors.toList());
            syncCustomerQuery.setDeviceUniqueIds(deviceUniqueIds);
        }

        String orderBy = OrderByUtil.getOrderBy(syncCustomerQuery.getOrderByField(), syncCustomerQuery.isAsc());
        PageHelper.startPage(syncCustomerQuery.getCurrent(), syncCustomerQuery.getSize(), orderBy);

        List<SyncCustomerJobVo> syncCustomerJobVoList = syncCustomerJobMapper.getSyncCustomerList(syncCustomerQuery);

        if (syncCustomerJobVoList != null && !syncCustomerJobVoList.isEmpty()) {
            for (SyncCustomerJobVo syncCustomerJobVo : syncCustomerJobVoList) {
                try {
                    WwDevice wwDevice = wwDeviceMapper.getById(syncCustomerJobVo.getDeviceUniqueId(), syncCustomerJobVo.getMerId());
                    if (wwDevice != null) {
                        syncCustomerJobVo.setDeviceName(wwDevice.getDeviceName());
                        syncCustomerJobVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return new MyPageInfo<>(syncCustomerJobVoList);
    }


    @Override
    public void delSyncCustomer(DelSyncCustomerDto delSyncCustomerDto) {
        if (delSyncCustomerDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (delSyncCustomerDto.getIds() == null || delSyncCustomerDto.getIds().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        for (Long id : delSyncCustomerDto.getIds()) {
            try {
                syncCustomerJobMapper.delById(id, delSyncCustomerDto.getMerId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }


    @Override
    @Async("taskExecutor")
    public void excuteSyncCustomer(BaseDto baseDto) {
        //获取一开始的任务，如果开始时间距离当前时间超过10分钟，则将状态修改为同步失败
        SyncCustomerQuery syncCustomerQuery = new SyncCustomerQuery();
        Long idStart = 0L;
        syncCustomerQuery.setMerId(baseDto.getMerId());
        syncCustomerQuery.setAsc(true);
        syncCustomerQuery.setCurrent(1);
        syncCustomerQuery.setSize(50);
        syncCustomerQuery.setOrderByField("id");
        syncCustomerQuery.setIdStart(idStart);
        syncCustomerQuery.setStatus(1);
        String orderBy = OrderByUtil.getOrderBy(syncCustomerQuery.getOrderByField(), syncCustomerQuery.isAsc());
        PageHelper.startPage(syncCustomerQuery.getCurrent(), syncCustomerQuery.getSize(), orderBy);
        List<SyncCustomerJobVo> syncCustomerJobVoList = syncCustomerJobMapper.getSyncCustomerList(syncCustomerQuery);
        while (syncCustomerJobVoList != null && !syncCustomerJobVoList.isEmpty()) {
            int nowTime = DateUtil.getTime();
            for (SyncCustomerJobVo syncCustomerJobVo : syncCustomerJobVoList) {
                try {
                    if (syncCustomerJobVo.getId().longValue() > idStart.longValue()) {
                        idStart = syncCustomerJobVo.getId();
                    }

                    if (nowTime - syncCustomerJobVo.getStartTime() > 600) {
                        SyncCustomerJob syncCustomerJob = syncCustomerJobMapper.getById(syncCustomerJobVo.getId(), syncCustomerJobVo.getMerId());
                        if (syncCustomerJob != null) {
                            syncCustomerJob.setStatus(3);
                            syncCustomerJobMapper.update(syncCustomerJob);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            syncCustomerQuery.setIdStart(idStart);
            PageHelper.startPage(syncCustomerQuery.getCurrent(), syncCustomerQuery.getSize(), orderBy);
            syncCustomerJobVoList = syncCustomerJobMapper.getSyncCustomerList(syncCustomerQuery);
        }


        //获取一个未开始的同步的任务
        SyncCustomerJob syncCustomerJob = syncCustomerJobMapper.getUnSyncCustomerTask(baseDto.getMerId());
        if (syncCustomerJob != null) {
            WwDevice wwDevice = wwDeviceMapper.getById(syncCustomerJob.getDeviceUniqueId(), syncCustomerJob.getMerId());
            MicaTriggerContactPushMsg micaTriggerContactPushMsg = new MicaTriggerContactPushMsg();
            micaTriggerContactPushMsg.setMessageId(IdWorker.getId());
            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerContactPushMsg, MicaTriggerType.TRIGGER_CONTACT_PUSH);
            micaTriggerDto.setMerId(wwDevice.getMerId());
            micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
            micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

            //设置更新通讯录时间
            wwDevice.setLastSyncCustomerTime(DateUtil.getTime());
            wwDeviceMapper.updateWwDevice(wwDevice);

            syncCustomerJob.setStatus(1);
            syncCustomerJob.setStartTime(DateUtil.getTime());
            syncCustomerJobMapper.update(syncCustomerJob);
        }
    }

    @Override
    public void syncPersonTag(SyncPersonTagDto syncCustomerDto) {
        if (syncCustomerDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (syncCustomerDto.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (syncCustomerDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        WwTags wwTags = wwTagsMapper.getById(syncCustomerDto.getId(), syncCustomerDto.getMerId());
        if (wwTags != null) {
            mqAddTagId(wwTags.getTagName(), wwTags.getId(), wwTags.getMerId(), wwTags.getDeviceUniqueId());
        }
    }

    @Override
    public void exportCustomerTags(CustomerQuery customerQuery, HttpServletResponse response) {
        if (customerQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (customerQuery.getFieldList() == null && customerQuery.getFieldList().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        customerQuery.setCurrent(1);
        customerQuery.setSize(10000);
        MyPageInfo<WwCustomerVo> wwCustomerVoMyPageInfo = getCustomer(customerQuery);
        if (wwCustomerVoMyPageInfo.getRecords() != null && !wwCustomerVoMyPageInfo.getRecords().isEmpty()) {
            List<WwCustomerVo> wwCustomerVoList = wwCustomerVoMyPageInfo.getRecords();
            wwCustomerVoList.forEach(it -> {
                it.setPersonTagNamesDesc();
                it.setWwtagNamesDesc();
                if (StringUtils.isBlank(it.getNickname())) {
                    if (!StringUtils.isBlank(it.getRemark())) {
                        it.setNickname(it.getRemark());
                    } else {
                        if (!StringUtils.isBlank(it.getName())) {
                            it.setNickname(it.getName());
                        }
                    }
                }
            });

            List<String> FieldsList = customerQuery.getFieldList().stream().map(SheetHeader::getDataIndex).distinct().collect(Collectors.toList());

            Map<String, String> replacements = new HashMap<>();
            replacements.put("wwtagNames", "wwtagNamesDesc");
            replacements.put("personTagNames", "personTagNamesDesc");
            List<String> Fields = FieldsList.stream().map(str -> replacements.getOrDefault(str, str)).collect(Collectors.toList());

            List<String> titles = customerQuery.getFieldList().stream().map(SheetHeader::getTitle).distinct().collect(Collectors.toList());

            // 使用Stream筛选匹配的字段
            List<Object> matchedObjects = wwCustomerVoList.stream().map(obj -> {
                Map<String, Object> matchedFields = new HashMap<>();
                Fields.forEach(field -> {
                    try {
                        Field objField = obj.getClass().getDeclaredField(field);
                        objField.setAccessible(true);
                        matchedFields.put(field, objField.get(obj));
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                });
                return matchedFields;
            }).filter(fieldsMap -> fieldsMap.size() == Fields.size()).collect(Collectors.toList());

            try {
                MyExcelUtil.exportExcel(response, titles, matchedObjects, Fields);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }

    @Override
    public WwCustomer getByWxId(@MerId Long merId, Long deviceUniqueId, String wxId) {
        return this.wwCustomerMapper.getByDeviceAndWxid(wxId, deviceUniqueId, merId);
    }

    @Override
    public Object getWwGroup(GetWwGroupQuery getWwGroupQuery) {
        if (getWwGroupQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (getWwGroupQuery.getCustomerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        //获取客户
        WwCustomer wwCustomer = wwCustomerMapper.getById(getWwGroupQuery.getCustomerId(), getWwGroupQuery.getMerId());
        if (wwCustomer == null) {
            return new MyPageInfo<>(null);
        }

        //获取客户所在的群微信ID列表
        WwGroupMemberQuery wwGroupMemberQuery = new WwGroupMemberQuery();
        wwGroupMemberQuery.setMerId(getWwGroupQuery.getMerId());
        wwGroupMemberQuery.setWxid(wwCustomer.getWxid());
        List<WwGroupMemberVo> wwGroupMemberList = wwGroupMemberMapper.getWwGroupMemberList(wwGroupMemberQuery);
        if (wwGroupMemberList == null || wwGroupMemberList.isEmpty()) {
            return new MyPageInfo<>(null);
        }
        List<String> groupWxids = wwGroupMemberList.stream().map(WwGroupMemberVo::getGroupWxid).distinct().collect(Collectors.toList());

        WwGroupQuery wwGroupQuery = new WwGroupQuery();
        wwGroupQuery.setGroupWxids(groupWxids);
        wwGroupQuery.setMerId(getWwGroupQuery.getMerId());
        wwGroupQuery.setCurrent(getWwGroupQuery.getCurrent());
        wwGroupQuery.setSize(getWwGroupQuery.getSize());
        wwGroupQuery.setOrderByField(getWwGroupQuery.getOrderByField());
        wwGroupQuery.setAsc(getWwGroupQuery.isAsc());
        MyPageInfo<WwGroupVo> wwGroupVoMyPageInfo = wwGroupService.getWwGroupList(wwGroupQuery);
        if (wwGroupVoMyPageInfo == null || wwGroupVoMyPageInfo.getRecords() == null || wwGroupVoMyPageInfo.getRecords().isEmpty()) {
            return new MyPageInfo<>(null);
        }

        List<GroupInfoVo> groupInfoVoList = new ArrayList<>();
        for (WwGroupVo wwGroupVo : wwGroupVoMyPageInfo.getRecords()) {
            try {
                GroupInfoVo groupInfoVo = new GroupInfoVo();
                BeanUtil.copyProperties(wwGroupVo, groupInfoVo);
                WwGroupMember wwGroupMember = wwGroupMemberMapper.getByGroupWxIdAndWxid(wwGroupVo.getGroupWxid(), wwCustomer.getWxid(), wwCustomer.getMerId());
                if (wwGroupMember != null) {
                    groupInfoVo.setJoinGroupTime(wwGroupMember.getCreateTime());
                }
                groupInfoVoList.add(groupInfoVo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        MyPageInfo<GroupInfoVo> groupInfoVoMyPageInfo = new MyPageInfo<>(groupInfoVoList);
        groupInfoVoMyPageInfo.setCurrent(wwGroupVoMyPageInfo.getCurrent());
        groupInfoVoMyPageInfo.setSize(wwGroupVoMyPageInfo.getSize());
        groupInfoVoMyPageInfo.setTotal(wwGroupVoMyPageInfo.getTotal());
        groupInfoVoMyPageInfo.setPages(wwGroupVoMyPageInfo.getPages());
        return groupInfoVoMyPageInfo;
    }

    @Override
    public void insert(WwCustomer customer) {
        wwCustomerMapper.insert(customer);
    }
}
